Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

My favorite solution

1
2
3
4
5
6
7
8
9
10
11
12
public class Solution {
public int reverse(int x) {
long rev = 0; // possible overflow
while ( x != 0) { // no need to take care of negative value
rev = rev * 10 + x % 10; // no need for an array to keep track of digits
x = x / 10;
if (rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE) // check for overflow while reversing
return 0;
}
return (int) rev;
}
}

My solution:

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) {
long rev = 0;
boolean neg = false;

if (x < 0){
neg = true;
x = -x;
}

while (x > 0){
rev = rev * 10 + x % 10;
x /= 10;
}

if (rev > (long) Integer.MAX_VALUE){return 0;}
if (neg){rev = -rev;}
return (int) rev;
}
}

Most voted solution on Leetcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Solution {
public int reverse(int x) {
int rev = 0;

while (x != 0){
int newR = rev * 10 + x % 10;
if ((newR - x % 10) / 10 != rev){return 0;}
rev = newR;
x /= 10;
}

return rev;
}
}