我已经写了下面的程序来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给我我以前的答案?这个想法是检查如果操作被颠倒过来,新的溢出值不会产生旧的结果。
如果这是一个错误的方法来检查溢出错误,任何人都可以启发我正确的方式来做到这一点?
我建议你用很长的计算值,或者你可以检查该值小于Integer.MAX_VALUE的/ 10 *做= 10.如果你等于需要额外的检查之前。 –