KEY points:
7. Reverse Integer
: overflow,Integer.MAX_VALUE
8. String to Integer (atoi)
: overflow,Integer.MAX_VALUE
better:
1 | class Solution { |
not so good:1
2
3
4
5
6
7
8
9
10
11class Solution {
public int reverse(int x) {
long res = 0;
while (x != 0) {
res = res * 10 + x % 10;
x /= 10;
if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) return 0;
}
return (int) res;
}
}
The 2nd solution is not general because it’s using a long type. This is specifically for this one problem, i.e. reverse a 32-bit integer
. What if it asks to reverse a 64-bit integer?: NOT GENERAL enough.
The better way is to check overflow instead of using larger data types.