Java中Integer.parse()的學習總結(jié)
來源:易賢網(wǎng) 閱讀:3745 次 日期:2015-04-10 14:48:56
溫馨提示:易賢網(wǎng)小編為您整理了“Java中Integer.parse()的學習總結(jié)”,方便廣大網(wǎng)友查閱!

內(nèi)部使用負數(shù)表示

當函數(shù)還未考慮到符號影響時候,內(nèi)部是用負數(shù)來表示逐步轉(zhuǎn)換的結(jié)果。

初看到下面兩句,很是疑惑。

int max = Integer.MIN_VALUE / radix;

int next = result * radix - digit;

為什么要用負數(shù)來表示呢?正數(shù)才比較符號平常頭腦的思路。

我的想法是,負數(shù)部分是0~-2147483648,而正數(shù)部分是0~2147483647,負數(shù)范圍比正數(shù)范圍廣。如果內(nèi)部是用正數(shù)的話,"-2147483648"這個字符串處理就更復(fù)雜點,因為正數(shù)沒法表示2147483648。

其他的理解放在下面代碼注釋中:

private static int parse(String string, int offset, int radix, boolean negative) throws NumberFormatException {

// Why is Integer.MIN_VALUE is choosed? Not Integer.MAX_VALUE ?

// Maybe because the range in the minus side is greater than that in the plus side

int max = Integer.MIN_VALUE / radix;

int result = 0;

int length = string.length();

while (offset < length) {

int digit = Character.digit(string.charAt(offset++), radix);

if (digit == -1) {

throw invalidInt(string);

}

//如果此時的result的絕對值已經(jīng)大于max的絕對值,那么result再增加一位必超出范圍。

//int max = Integer.MIN_VALUE / radix; 這是max定義。

if (max > result) {

throw invalidInt(string);

}

int next = result * radix - digit;

//可能出現(xiàn)overflow的現(xiàn)象。

//如:如果radix為10,上面result等于-214748364,又digit大于8,則next會超出范圍。

if (next > result) {

throw invalidInt(string);

}

result = next;

}

if (!negative) {

result = -result;

// when result equals to 80000000H, -result equals to result.

if (result < 0) {

throw invalidInt(string);

}

}

return result;

}

更多信息請查看IT技術(shù)專欄

更多信息請查看網(wǎng)絡(luò)編程
易賢網(wǎng)手機網(wǎng)站地址:Java中Integer.parse()的學習總結(jié)

2025國考·省考課程試聽報名

  • 報班類型
  • 姓名
  • 手機號
  • 驗證碼
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機站點 | 投訴建議
工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號
聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關(guān)注公眾號:hfpxwx
咨詢QQ:1093837350(9:00—18:00)版權(quán)所有:易賢網(wǎng)