Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Example2: x = -123, return -321
int reverse(int x) {
if(x == 0)
return 0;
bool isneg = false;
if(x < 0)
{
x = -x;
isneg = true;
}
int result = 0;
while(x)
{
int t = x % 10;
x = x / 10;
result = result * 10 + t;
}
if(isneg)
return -result;
else
return result;
}
No comments:
Post a Comment