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 .