2017-05-10 45 views
0

我已經寫了下面的程序來ATOI(字符串到整數轉換)。我試圖檢測整數溢出錯誤,如果我的正在進行的答案是高於或低於它。 但我得到以下錯誤。整數溢出查詢

public class Solution { 
public int myAtoi(String str) { 
    int index = 0; 
    boolean isPos = true; 
    int temp = 0; 
    int ans = 0; 
    int present = 0; 
    if(str==null || str.length()==0){ 
     return 0; 
    } 
    while(index<str.length() && (str.charAt(index)<48 || str.charAt(index)>57)){ 
     index++; 
    } 
    if(index-1>=0 && str.charAt(index-1)=='-'){ 
     isPos = false; 
    } 
    if(index<str.length()){ 
     ans = str.charAt(index++)-'0'; 
    } 
    else{ 
     return 0; 
    } 
    while(index<str.length() && (str.charAt(index)>=48 && str.charAt(index)<=57)){ 
     present = str.charAt(index)-'0'; 
     temp = ans*10 + present; 
     System.out.println("ans= "+ans + " temp= "+temp + " (temp-present)/10= "+ (temp-present)/10); 
     if((temp-present)/10 != ans){ 
      ans = Integer.MAX_VALUE; 
      break; 
     } 
     ans = temp; 
     index++; 
    } 
    if(!isPos){ 
     ans = -ans; 
    } 

    return ans; 
} 
} 

對上述輸出出來是:

ans= 2 temp= 21 (temp-present)/10= 2 
ans= 21 temp= 214 (temp-present)/10= 21 
ans= 214 temp= 2147 (temp-present)/10= 214 
ans= 2147 temp= 21474 (temp-present)/10= 2147 
ans= 21474 temp= 214748 (temp-present)/10= 21474 
ans= 214748 temp= 2147483 (temp-present)/10= 214748 
ans= 2147483 temp= 21474836 (temp-present)/10= 2147483 
ans= 21474836 temp= 214748364 (temp-present)/10= 21474836 
ans= 214748364 temp= -2147483648 (temp-present)/10= 214748364 

誰能告訴我爲什麼我的溫度將是預期負數,但的計算(臨時至今)/10給我我以前的答案?這個想法是檢查如果操作被顛倒過來,新的溢出值不會產生舊的結果。

如果這是一個錯誤的方法來檢查溢出錯誤,任何人都可以啓發我正確的方式來做到這一點?

+0

我建議你用很長的計算值,或者你可以檢查該值小於Integer.MAX_VALUE的/ 10 *做= 10.如果你等於需要額外的檢查之前。 –

回答

0

如果你想防止溢出,請使用「精確」方法Math(在Java中加入8):

// Old code 
temp = ans*10 + present; 
// New code 
try { 
    temp = Math.addExact(Math.multiplyExact(ans, 10), present); 
} catch (ArithmeticException e) { 
    temp = Integer.MAX_VALUE; 
} 

或者,如果你不想這樣做,因爲present是一個數字0-9,下面的測試就足夠了,因爲用於temp小於ans的唯一方法,是溢出負值:

if (temp < ans) // overflowed 
0

Integer類有一個最小值-2,147,483,648和2,147,483,647最大值(含)

temp= 214748364後的迭代如下

present = str.charAt(index)-'0'; // saves the integer 8 
temp = ans*10 + present;   // 2147483640 + 8 

爲了更好的理解,讓我們把它分解
2147483640 + 7 + 1 = 2147483647 (which is the max limit) + 1
通過整數範圍內這將循環,從而得到改變,以-2147483648

寫檢查,以檢測溢出,你可以簡單地比較anstemp值。

if(ans > temp) { 
    // there was an overflow 
    ... 
} 
+0

是的,我知道它已經循環並且已經變成-2147483648,這是一個負值。但是我要問的是,當我用(臨時存在)/ 10反轉該操作時,它導致了正確的前一個答案,它應該不是214748364? 我正在逆轉負數上的操作嗎?它應該給我一個錯誤的答案(這是我的支票),但它給了我正確的數字,這就是爲什麼檢查失敗。 – MrConsigliere

+0

對不起,我沒有得到你。你能用一個例子來解釋它會失敗嗎? –