Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
class Solution {
public:
int reverse(int x) {
int result = 0;
int flag = false;
if(x < 0)
{
flag = true;
x = -x;
}
while(x > 9)
{
int y = x % 10;
x = x / 10;
result = result * 10 + y;
}
result = result * 10 + x;
if(flag == true)
{
result = -result;
}
return result;
}
};
代码更简洁的方法:
class Solution {
public:
int reverse(int x) {
int result = 0;
while(x != 0)
{
result = result * 10 + x % 10;
x /= 10;
}
return result;
}
};