您的位置:首页 > 其它

数字倒序

2017-05-16 17:05 706 查看
Reverse digits of an integer.

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

click to show spoilers.

Note:

The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

代码如下:

public class ReverseInteger {

public int reverse(int x){
int result = 0;

while(x!=0){
int tail = x%10;
int newResult = result*10 + tail;
if((newResult - tail)/10 != result){
return 0;
}
result = newResult;
x = x/10;
}

return x>=0 ? result : -result;//考虑符号问题
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息