KEY points:

  1. 7. Reverse Integer: overflow, Integer.MAX_VALUE
  2. 8. String to Integer (atoi): overflow, Integer.MAX_VALUE

better:

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int reverse(int x) {
int prev =0, res = 0;
while (x != 0) {
res = res * 10 + x % 10;
if ((res - x % 10) / 10 != prev) return 0;
prev = res;
x /= 10;
}
return res;
}
}

not so good:

1
2
3
4
5
6
7
8
9
10
11
class 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.