007.Reverse Integer

Test cases

1
2
3
4
5
6
7
8
10000
123321
-2147483412
2147483412
-2147483648
2147483647
1534236469
-1534236469

Solution 1: accepted

Basicly hard code, not wise at all.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
public int reverse(int x) {
int reversed = 0;
int digit = 0;
while (x != 0) {
if (digit == 9) {//2147483648
if (reversed > 214748364 || reversed < -214748364)
return 0;
else if (reversed == 214748364 && x % 10 >7)
return 0;
else if (reversed == -214748364 && x % 10 >8)
return 0; // not happening as input is int
}
reversed = reversed * 10 + x % 10;
x = x / 10;
digit++;
}
return reversed;
}
}

Solution 2: accepted 41ms, 54%

Concise and fast. A smart way to detect overflow.

1
2
3
4
5
6
7
8
9
10
11
12
public int reverse(int x) {
int reversed = 0;
while (x != 0) { // x could be negative
int before = reversed;
   int tail = x % 10; // this improves speed
reversed = reversed * 10 + tail;
if ((reversed - tail) / 10 != before) // check overflow
return 0;
x /= 10;
}
return reversed;
}

Solution 3: accepted 36ms 92%

Even more concise and faster! Jump out of the “box”!

1
2
3
4
5
6
7
8
9
10
public int reverse(int x) {
long reversed = 0;
while (x != 0) {
reversed = reversed * 10 + x % 10;
if (reversed > Integer.MAX_VALUE || reversed < Integer.MIN_VALUE )
return 0;
x /= 10;
}
return (int)reversed;
}