[LeetCode] 7. Reverse Integer 翻轉整數


 

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.

 
 
翻轉數字問題需要注意的就是溢出問題,看了許多網上的解法,由於之前的 OJ 沒有對溢出進行測試,所以網上很多人的解法沒有處理溢出問題也能通過 OJ。現在 OJ 更新了溢出測試,所以還是要考慮到。為什么會存在溢出問題呢,由於int型的數值范圍是 -2147483648~2147483647, 那么如果要翻轉 1000000009 這個在范圍內的數得到 9000000001,而翻轉后的數就超過了范圍。博主最開始的想法是,用 long 型數據,其數值范圍為 -9223372036854775808~9223372036854775807, 遠大於 int 型這樣就不會出現溢出問題。但實際上 OJ 給出的官方解答並不需要使用 long,一看比自己的寫的更精簡一些,它沒有特意處理正負號,仔細一想,果然正負號不影響計算,而且沒有用 long 型數據,感覺寫的更好一些,那么就貼出來吧:

 

解法一:

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

 

類似題目:

String to Integer (atoi)

Reverse Bits

 

參考資料:

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

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM