我已經寫了下面的程序來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.如果你等於需要額外的檢查之前。 –