标签:末尾 数字逆转 integer c++ leetcode
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
取一个数的最后一位,用x % 10
,取一个数的前n-1位(共n位),用x/10
,每一次取的时候,都将上一次取的数乘以10,然后再加上末尾的数即可,代码如下:
Code(C++)
class Solution {
public:
int reverse(int x) {
long result = 0;
while(x != 0)
{
result = result*10 + x % 10;
x /= 10;
}
return (result > INT_MAX || result < INT_MIN)? 0 : result;
}
};
标签:末尾 数字逆转 integer c++ leetcode
原文地址:http://blog.csdn.net/dream_angel_z/article/details/46476481