原题
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 int Reverse(int x)
{
bool isNegative = x < 0;
long rtn = 0;
while (x != 0)
{
int postBit = x%10;
long iterval = rtn*10 + postBit;
if (isNegative && iterval < -2147483648) return 0;
if (iterval > 2147483647) return 0;
rtn = iterval;
x /= 10;
}
return (int)rtn;
}
一种不适用最大值和最小值的判断溢出方法:
public static int Reverse(int x)
{
int rtn = 0;
while (x != 0)
{
int postBit = x % 10;
//if happens overflow, rtn!= (iterval - postBit)/10
int iterval = rtn * 10 + postBit;
if ((iterval - postBit) / 10 != rtn) //solve the overflow
{
return 0;
}
rtn = iterval;
x = x / 10;
}
return rtn;
}
leetcode-solution库
leetcode算法题目解决方案每天更新在github库中,欢迎感兴趣的朋友加入进来,也欢迎star,或pull request。https://github.com/jackzhenguo/leetcode-csharp