LeetCode2:整數反轉

集思廣益
題意描述:
給出一個 32 位的有符號整數,你需要將這個整數中每位上的數字進行反轉。

注意:
假設我們的環境只能存儲得下 32 位的有符號整數,則其數值範圍爲 [−231, 231 − 1]。請根據這個假設,如果反轉後整數溢出那麼就返回 0。

示例:

示例 1:
輸入: 123
輸出: 321

示例 2:
輸入: -123
輸出: -321

示例 3:
輸入: 120
輸出: 21

解法1:

class Solution {
    public int reverse(int x) {
        String a = Integer.toString(x);
        int b = 1;
        if(a.charAt(0) == '-'){
            a = a.substring(1);
            b = -1;
        }
        char[] char1 = a.toCharArray();
        char[] result = new char[char1.length];
        for(int i = char1.length - 1; i >= 0; i--){
            result[char1.length - 1- i ] = char1[i];
        }
        //判斷有沒有溢出
        Long value = Long.valueOf(new String(result));
        if(value > Integer.MAX_VALUE || value < Integer.MIN_VALUE){
            return 0;
        }
        return (int) (value * b);
        
    }
}

解法2:

class Solution {
    public int reverse(int x) {
        int a;
        long b = 0;
        while(x != 0){
            a = x % 10;
            x = x / 10;
            b = b * 10 + a;
        }
        if(b > Integer.MAX_VALUE || b < Integer.MIN_VALUE){
            return 0;
        }
        return (int) b;
    }
}

解法3:
真牛逼。。

class Solution {
    public int reverse(int x) {
        long a = 0;
        while(x != 0){
            a = a * 10 + x % 10;
            x /= 10;
        }
        return (a < Integer.MIN_VALUE || a > Integer.MAX_VALUE) ? 0:(int) a;
    }
}
發佈了26 篇原創文章 · 獲贊 4 · 訪問量 4454
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章