鍍金池/ 問答/人工智能  Java  HTML/ java反轉(zhuǎn)字符串邊界溢出

java反轉(zhuǎn)字符串邊界溢出

反轉(zhuǎn)一個(gè)十進(jìn)制數(shù),正負(fù)數(shù)邊界溢出報(bào)錯(cuò),邊界設(shè)定了,為什么還是溢出?

class Solution {
    public int reverse(int x) {
      
        String s=new StringBuffer(Math.abs(x)+"").reverse().toString();  
        Integer newValue = Integer.valueOf(s);  
        
        if(x>0){  
            if(newValue>Integer.MAX_VALUE ||newValue<Integer.MIN_VALUE){  
                return 0;  
            }else{  
                return (int) newValue;  
            }  
        }else{  
              
                return (int)(0-newValue);  
              
        }  
    }
}
public class MainClass {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = in.readLine()) != null) {
            int x = Integer.parseInt(line);
            
            int ret = new Solution().reverse(-2147483648);
            
            String out = String.valueOf(ret);
            
            System.out.print(out);
        }
    }
} 

錯(cuò)誤:
Error:
Line 5: java.lang.NumberFormatException: For input string: "8463847412-"

回答
編輯回答
拼未來

其實(shí):

Math.abs(-2147483648) == -2147483648

很有意思吧?

2017年6月3日 14:16
編輯回答
忘了我

樓上說的沒錯(cuò)。請查閱Math.abs()方法(參數(shù)為 int)的文檔注釋,片段如下:

Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.

當(dāng)方法的參數(shù)值等于 int 最小值時(shí),結(jié)果為原值。

2017年5月13日 16:11