2017-05-10 59 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

对不起,我没有得到你。你能用一个例子来解释它会失败吗? –