题目:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
思路
题目计较简单,直接上代码吧!
代码:
class Solution {
public:
int reverse(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
bool reverse = false;
if(x < 0)
{
reverse = true;
x = -x;
}
int result = 0;
while(x > 0)
{
int temp = x % 10;
if(INT_MAX / 10 < result){
return 0;
}
else if(INT_MAX / 10 == result && INT_MAX % 10 < temp){
return 0;
}
result *= 10;
result += temp;
x /= 10;
}
if(reverse)
{
return -result;
}
else
return result;
}
};