題目
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
NOTE:The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
解題思路:
這個題目是讓我們反轉一個整數,需要我們留意溢出的問題
- 從各位開始分別取出 個位 十位 百位... 上的數值,比如 123 ,個位就是 3, 十位數字是 2,那就是20,百位數字是1,那就是100。反轉過來就是 3100 + 210 + 1 = 321
- 最后需要判斷一下反轉后的數字是否在 32 位 int 表示范圍內溢出
解題代碼:
class Solution {
public:
int reverse(int x) {
// int 類型的 x 反轉后可能會產生溢出,所以我們使用 long long 類型來存放反轉后的數字
long long num = 0;
// 對于 c/c++ 來說 0 是 false,其他非 0 都是 true
while (x) {
num = num * 10 + x%10;
x = x / 10;
}
// 判斷是否產生溢出
if (num > INT_MAX || num < INT_MIN) {
num = 0;
}
return num;
}
};