LeetCode 7. Reverse Integer題解

題目

7. Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.
給出一個 32 位的有符號整數,你需要將這個整數中每位上的數字進行反轉。

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21


分析

思路一:利用StringBuilder特性

這是一個暴力解法,但有必要知道。Java中對StringBuilder直接提供了一個reverse(字符串翻轉)方法,因而我們將輸入的整形轉爲StringBuilder類型並調用reverse進行翻轉後,再轉爲整形返回即可。其間我們利用try-catch來處理可能出現的溢出問題。

思路二:按位依次翻轉

這是非常常規的解法。舉一個具體的例子分析(假定輸入是input,輸出是output):

input = 123; output = 321;

分析如下:
input = 123 = 3 * 100 + 2 * 101 + 1 * 102
output = 3 * 102 + 2 * 101 + 1 * 100 = 321
先假設不考慮溢出:

class Solution {
    public int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            //這裏補充處理溢出問題的代碼
            rev = rev * 10 + pop;
        }
        return rev;
    }
}

接下來補充處理溢出的部分:

            if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
            if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;

這裏是考慮到32位有符號整形的範圍-2147483648——2147483647,因而需要考慮pop > 7pop < -8


題解

Java實現思路一

class Solution {
    public int reverse(int x) {
        boolean flag = x > 0;
        String s;
        if(flag)s = x + "";
        else s = -x + "";
        StringBuilder b = new StringBuilder(s);
        s = b.reverse().toString();
        int returnInt;
        try{
            returnInt = Integer.parseInt(s);
        }catch (Exception e){
            return 0;
        }
        return flag?returnInt:-returnInt;
    }
}

Java實現思路二



class Solution {
    public int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
            if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }
}

C++實現思路二

class Solution {
public:
    int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
            if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }
};

其中思路二也即LeetCode官方題解。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章