Question:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
分析:
倒置整形数字,借用字符串,因为可以通过atoi,atol,atoll,atof,strtod,strtol,strtoul等函数将字符串转换为数字;
按顺序用字符串的每一位存放数字中的每一位;
代码如下:
<span style="font-size:14px;">class Solution {
public:
int reverse(int x) {
string s = "";
bool isNgt = false;
long result = 0;
if(x == INT_MIN || x == 0)
return 0;
if(x < 0){
isNgt = true;
x = -x;
}
while(x % 10 == 0)
x /= 10;
while(x){
int tmp = x % 10;
s += to_string(tmp);
x /= 10;
}
result = atol(s.c_str());
if(isNgt)
result = -result;
if(result < INT_MIN || result > INT_MAX)
return 0;
return (int)result;
}
};</span>