Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
题目咋看起来很简单,其实,真的很简单:
class Solution
{
public:
int reverse(int x)
{
int ret = 0;
bool isNegative = false;
if (x < 0)
{
isNegative = true;
x = -x;
}
while (x)
{
ret = ret * 10 + x % 10;
x /= 10;
}
return ret * (isNegative? -1 : 1);
}
};7 % 2 = 1
7 % -2 = 1
-7 % 2 = -1
-7 % -2 = -1
所以,正数取余,永远是正数(或者0);负数也是同样的道理;0当然永远都是0啦。
因此,我们的程序可以再简单一点:
class Solution
{
public:
int reverse(int x)
{
int ret = 0;
while (x)
{
ret = ret * 10 + (x % 10);
x /= 10;
}
return ret;
}
};注意细节,说不定某天你就变成大牛了。
【Leet Code】Reverse Integer——“%”你真的懂吗?
原文:http://blog.csdn.net/u012771236/article/details/38826047