題目: LeetCode - 7. Reverse Integer

題目說明

給一個整數,將此整數反轉。

解題思路

從最後面一位一位拿出來即可,需要特別注意若是過程中超過 int 的界限就直接回傳 0。

參考解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int reverse(int x) {
int ans = 0, max = INT_MAX / 10, min = INT_MIN / 10;
while(x != 0)
{
if(ans > max || ans < min)
return 0;
ans = ans * 10 + x % 10;
x /= 10;
}
return ans;
}
};