LeetCode Reverse Integer(007)解法總結

NewCoder1024發表於2020-03-13

描述

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.

思路

覺得使用int型別取餘比較麻煩,就使用字串逆序讀取。

這裡使用的是手動迴圈逆序,在逆序的同時消除開頭的0。一開始使用Integer.parseInt()將轉換完的StringBuffer化為int,忽視了要求最後的如果翻轉完後溢位的處理

LeetCode Reverse Integer(007)解法總結

後來改為用long型記錄資料(按進位將每個數字相加),並且和Integer.MAX_VALUE相比較,如果發生溢位就返回0.

class Solution {
    public int reverse(int x) {
        boolean posi = true, allZero = true;
        if(x<0){
            posi = false;
            x = -x;
        }

        //字串逆序去0處理
        String temp = Integer.toString(x);
        StringBuffer sb = new StringBuffer();
        for(int i = temp.length()-1; i>=0; i--){
            if(temp.charAt(i) != '0'){
                allZero = false;
            }
            if(!allZero){
                sb.append(temp.charAt(i));
            }
        }
        
        //使用long防止溢位
        temp = sb.toString();
        long check = 0;
        for(int i = 0;i<temp.length();i++){
            check = check * 10 + temp.charAt(i) - '0';
            if(check > (long)Integer.MAX_VALUE){
                return 0;
            }
        }
        
        //返回值
        if(posi){
            return (int)check;
        }else{
            return -(int)check;
        }
    }
}複製程式碼
Runtime: 1 ms, faster than 100.00% of Java online submissions for Reverse Integer.
Memory Usage: 37.2 MB, less than 5.55% of Java online submissions for Reverse Integer.

另一種思路

評論區見到的,使用除法和求餘。並判斷兩個數字的關係來確定是否發生了溢位。

Only 15 lines.
If overflow exists, the new result will not equal previous one.
No flags needed. No hard code like 0xf7777777 needed.

class Solution {
    public int reverse(int x){
    int result = 0;

    while (x != 0){
        int tail = x % 10;
        int newResult = result * 10 + tail;
        if ((newResult - tail) / 10 != result)
        { return 0; }
        result = newResult;
        x = x / 10;
    }

    return result;
    }
}複製程式碼
Runtime: 1 ms, faster than 100.00% of Java online submissions for Reverse Integer.
Memory Usage: 37 MB, less than 5.55% of Java online submissions for Reverse Integer.

時間和空間消耗相差不多。

相關文章