[英]Integer Overflow Query
我已經為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會給我以前的數值嗎? 想法是檢查如果操作相反,新的溢出值將不會產生舊的結果。
如果這是檢查溢出錯誤的錯誤方法,那么有人可以啟發我正確的方法嗎?
如果要防止溢出,請使用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
整數類的最小值為-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
。
這將在Integer范圍內循環,因此更改為-2147483648
要編寫檢查以檢測溢出的方法,您可以簡單比較ans
和temp
值。
if(ans > temp) {
// there was an overflow
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.