您的位置:首页 > 其它

Reverse Integer(leetcode7)

2017-08-09 15:17 357 查看
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.

解题思路:通过对x%10不断得到当前x最后一位的数字,加到反转后的数字当中,最后再判断一下是否超出范围就可以了。借助了一个long型局部变量有点投机取巧。

public class Solution {
public  int reverse(int x) {
int count = 0;	//记录已经操作的位数
long reverseNum = 0;	//反转后的数
while (x != 0) {
reverseNum = x % 10 + (reverseNum * 10);
x /= 10;
count++;
if (count == 10)	//判断是否超过32位整数的范围
if (reverseNum >= Integer.MAX_VALUE || reverseNum < Integer.MIN_VALUE)
return 0;
}
return (int)reverseNum;
}
}


discuss高赞答案,无须long型局部变量,加多一个判断语句即可检查是否超出范围,非常巧妙。
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 result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: