class Solution {
public:
int reverse(int x) {
int index = 1, sum = 0;
vector<int> res;
while (int(abs(x) / pow(10, index - 1)) > 0) {
res.push_back(int(abs(x) % int(pow(10, index)) / pow(10, index - 1)));
index++;
}
for (int i = 0; i < res.size(); i++) {
sum += res[i] * pow(10, index - 2);
index--;
}
if (0 > sum) {
return 0;
}
return x < 0 ? -sum : sum;
}
};
改進做法
class Solution {
public:
int reverse(int x) {
int index = 1, sum = 0;
int t = abs(x);
while (t > 0) {
if(sum > INT_MAX/10 || sum<INT_MIN/10){
return 0;
}
int res = t % 10;
sum = sum * 10 + res;
t = t /10;
}
return x < 0 ? -sum : sum;
}
};