Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
保留符号翻转数字,如果int溢出则返回0;用vector储存每一位数字,注意0的处理。对于溢出的判断我随便写了对符号进行判断没想到就ac了,不知道LeetCode的case覆盖全不全,这样做有没有问题。
class Solution {
public:
int reverse(int x) {
int f = 1;
if (x < 0) {
f = -1;
x = -x;
}
vector<int>v1;
while (x) {
int t = x % 10;
if((!v1.empty())||t)
v1.push_back(t);
x /= 10;
}
int i, ans = 0;
for (i = 0; i < v1.size(); i++)
{
ans += v1[i] * pow(10, v1.size() - i - 1);
}
ans *= f;
if (ans * f < 0) return 0;
return ans;
}
};