# LeetCode之路第七题

Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

public static int test(int x) {

if (x > 0) {

String str =x + "";

char[] a = str.toCharArray();

int j = a.length - 1;

for (inti = 0; i < a.length / 2; i++) {

char temp = a[i];

a[i] =a[j];

a[j--] =temp;

}

str = String.valueOf(a);

x = Integer.parseInt(str);

returnx;

} else if (x < 0) {

x = x * -1;

String str =x + "";

char[] a = str.toCharArray();

int j = a.length - 1;

for (inti = 0; i < a.length / 2; i++) {

char temp = a[i];

a[i] =a[j];

a[j--] =temp;

}

str = String.valueOf(a);

return Integer.parseInt(str) * -1;

}

return 0;

}

Runtime Error Message:Line 14: java.lang.NumberFormatException: For input string: "9646324351"

Last executed input:1534236469

public int reverse(int x) {
int ans=0;
while(x!=0){
int temp=ans*10+x%10;
if(temp/10!=ans){//如果此时temp和ans不相等那么说明temp越界了，这个设计省去了很多麻烦
return 0;
}
ans=temp;
x/=10;
}
return ans;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120