Hi, this is Shunchi!

  • Home

  • Tags0

  • Archives267

  • Categories0

  • Curricula

  • DSA

  • LeetCode_Notes

  • Interviews

  • General

  • Resume

7. Reverse Integer

Posted on 2020-06-13 | Edited on 2021-01-22

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;
}
}

<1…165166167…267>
ShunchiZhou

ShunchiZhou

267 posts
RSS
GitHub E-Mail Gitbook Linkedin
© 2024 ShunchiZhou
Powered by Hexo v5.4.0
|
0%