Reverse digits of an integer.
Example1: x = 123, return 321
Example1: x = 123, return 321
Example2: x = -123, return -321
判断正负,用余数和商迭代计算。
class Solution{
public:
int reverse(int x){
bool positive = true;
if(x < 0){//判断正负
x = 0 - x;
positive = false;
}
int temp = 0;
int i;
while(x != 0){
i = x % 10;
temp = temp * 10 + i;
x = x / 10;
}
if(!positive)
temp = 0 - temp;
return temp;
}
};