7. Reverse Integer

LeetCode

Approach 1: using long

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int reverse(int x) {
long ans = 0;
while(x != 0){
ans= ans*10;
ans+= x% 10;
x= x/10;
}

if (ans > Integer.MAX_VALUE || ans< Integer.MIN_VALUE) return 0;
else return (int)ans;
}
}

Approach 2: not using long (explanation)

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

0%