Reverse Integer

目录

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.
Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Update (2014-11-10):
Test cases had been added to test the overflow behavior.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class Solution {
public int reverse(int x) {
//几种特殊情况,100,反转去前导0;超过int范围的返回0。注意符号。
List<Integer> arrayList = new ArrayList<Integer>();
if(x==0){
return 0;
}
int ss = 1;
for(;;){
//求余;
int r = x%ss;
if(r==0&&x<ss){
break;
}else{
arrayList.add(r);
ss*=10;
}
}
double dd = 0;
for(int i=arrayList.size()-1;i>0;i--){
dd += arrayList.get(i)*(Math.pow(10,i));
}
if(dd>Math.pow(2,16)){
return 0;
}
int ri = (int)dd;
if(x<0){
return 0-ri;
}else{
return ri;
}
}
}
///Runtime Error
Runtime Error Message: Line 12: java.lang.ArithmeticException: / by zero
Last executed input: 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//逻辑混乱
public class Solution {
public long g(long xx,long g){
if(g==10){
return (xx%g);
}
if(xx<g){
return (xx-xx%(g/10))/(g/10);
}
return ((xx%g)-xx%(g/10))/(g/10);
}
public int reverse(int x) {
//几种特殊情况,100,反转去前导0;超过int范围的返回0。注意符号。
List<Long> arrayList = new ArrayList<Long>();
boolean zf = true;
if(x<0)zf=false;
if(x==0){
return 0;
}
long ss = 10;
double sss = 1;
if(x>Math.pow(2,31)-1||x<-Math.pow(2, 31)){
return 0;
}else if(x>-10&&x<10){
return x;
}
x=Math.abs(x);
for(;;){
//求余;
if(x<sss)break;
//int r = x%ss;
long r = g(x, ss);
arrayList.add(r);
ss=ss*10;
sss=sss*10;
}
double dd = 0;
for(int i=0,j=arrayList.size()-1;i<arrayList.size();i++,j--){
dd += arrayList.get(i)*(Math.pow(10,j));
}
if(dd>Math.pow(2,31)){
return 0;
}
int ri = (int)dd;
if(!zf){
return 0-ri;
}else{
return ri;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
//厉害答案。。。
public int reverse(int x) {
int ret = 0;
while (x != 0) {
// handle overflow/underflow
if (Math.abs(ret) > 214748364) {
return 0;
}
ret = ret * 10 + x % 10;
x /= 10;
}
return ret;
}