[英]Java integer overflow
我對Java完全Leetcode
並且正在實現一個簡單的函數,以在Leetcode
字符串轉換為整數。
public int myAtoi(String str) {
if(str.length() == 0){
return 0;
}
str = str.trim();
int n = str.length();
int signal = 0;
if(n == 1 && str.equals("+") || str.equals("-")){
return 0;
}
if(str.charAt(0) == '+'){
signal = 1;
}else if(str.charAt(0) == '-'){
signal = -1;
}
int i = (signal != 0)? 1 : 0;
if(signal == 0){
signal = 1;//default
}
int res = 0;
while(i < n){
char c = str.charAt(i);
if(!Character.isDigit(c)){
return res * signal;
}
//res = res * 10 + c - '0';
if(signal * res > Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
if(signal * res < Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
res = res * 10 + c - '0';
++i;
}
return res * signal;
}
我知道java整數具有2147483647
的MAX_VALUE
。 當我的輸入是2147483648
,輸出應該是2147483647
但實際上是-214748648
。 我真的不知道這里有什么問題。 有人可以幫助我了解這一點嗎?
輸入永遠不會為+2147483648,因為該值不能表示為Java int。
它將環繞到您觀察到的負數,因此考慮了該結果。
考慮這個例子
public static void main(String args[]) {
int i=2147483647;
System.out.println("i="+i);
int j=++i;
System.out.println("Now i is="+i);
System.out.println("j="+j);
}
怎么了? 輸出將是:
i = 2147483647
Now i is=-2147483648
j=-2147483648
整數的最大值是2,147,483,647,最小值是-2,147,483,648。 在j(后增量為i)中,我們越過了整數的最大限制
這正是您的情況。
因為整數溢出。 溢出時,下一個值為Integer.MIN_VALUE
為什么?
整數值以二進制形式表示,並且在Java中有二進制加法。 它使用稱為二進制補碼的表示形式,其中數字的第一位表示其符號。 每當將1加到最大Integer(MAX INT)(其位符號為0)時,其位符號都將變為1,並且數字變為負數。
因此,請勿將> MAX INT用作輸入,否則請在代碼中放入條件以檢查輸入本身。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.