LeetCode_java_7整數反轉

class Solution {
    public int reverse(int x) {
        int ans = 0;
        while(x != 0){
            int tail = x % 10;
            int newAns = ans * 10 + tail;
            //超過Integer的最大值後,正整數會變成負數;
            if(newAns / 10 != ans){ return 0;}
            ans = newAns;
            x = x / 10;
        }
        return ans;
    }
}



Nice solution, but, as many others, I didn’t get the line if ((newResult - tail) / 10 != result).
We’re interested on what happens when an integer overflows. Well, it is rolled over. Practically speaking, if you would try

    public static void main(String[] args) {
        int rollMeOver= Integer.MAX_VALUE + 1;
        System.out.println(rollMeOver);
    }

You will get as an output -2147483648 which represents the lowest value for an integer (Integer.MIN_VALUE).
Thus, in our problem, if newResult is going to overflow we are sure that newResult / 10 != result (this is the reason that @Inception_wzd said that we don’t need to subtract the tail first because by / 10 we are already losing the last digit).
By the way, the same thing happens for the underflow.

   public static void main(String[] args) {
        int rollMeOver= Integer.MIN_VALUE - 1;
        System.out.println(rollMeOver);
    }

This is going to output the Integer.MAX_VALUE which is 2147483647 .

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章