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 store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
解法一:
class Solution { public: int reverse(int x) { int res = 0; while (x != 0) { if (abs(res) > INT_MAX / 10) return 0; res = res * 10 + x % 10; x /= 10; } return res; } };
在貼出答案的同時,OJ 還提了一個問題 To check for overflow/underflow, we could check if ret > 214748364 or ret < –214748364 before multiplying by 10. On the other hand, we do not need to check if ret == 214748364, why? (214748364 即為 INT_MAX / 10)
為什么不用 check 是否等於 214748364 呢,因為輸入的x也是一個整型數,所以x的范圍也應該在 -2147483648~2147483647 之間,那么x的第一位只能是1或者2,翻轉之后 res 的最后一位只能是1或2,所以 res 只能是 2147483641 或 2147483642 都在 int 的范圍內。但是它們對應的x為 1463847412 和 2463847412,后者超出了數值范圍。所以當過程中 res 等於 214748364 時, 輸入的x只能為 1463847412, 翻轉后的結果為 2147483641,都在正確的范圍內,所以不用 check。
我們也可以用 long 型變量保存計算結果,最后返回的時候判斷是否在 int 返回內,但其實題目中說了只能存整型的變量,所以這種方法就只能當個思路擴展了,參見代碼如下:
解法二:
class Solution { public: int reverse(int x) { long res = 0; while (x != 0) { res = 10 * res + x % 10; x /= 10; } return (res > INT_MAX || res < INT_MIN) ? 0 : res; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/7
類似題目:
參考資料:
https://leetcode.com/problems/reverse-integer/
https://leetcode.com/problems/reverse-integer/discuss/4060/My-accepted-15-lines-of-code-for-Java
https://leetcode.com/problems/reverse-integer/discuss/4056/Very-Short-(7-lines)-and-Elegant-Solution