1. 程式人生 > >【LeetCode】整數反轉

【LeetCode】整數反轉

給出一個 32 位的有符號整數,你需要將這個整數中每位上的數字進行反轉。

示例 1:

輸入: 123
輸出: 321

 示例 2:

輸入: -123
輸出: -321

示例 3:

輸入: 120
輸出: 21

注意:

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


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int n=sc.nextInt();
        int reu=Solution.reverse(n);
        System.out.println(reu);

    }
}

class Solution {
    public static int reverse(int x) {

        int reu=0;
        while (x!=0)
        {
            int pop = x % 10;//彈出最後一位
            x/=10;

            /*
            判斷結果是否會溢位:
            */
            if (reu>Integer.MAX_VALUE/10||(reu==Integer.MAX_VALUE/10&&pop>7)) return 0;
            if (reu<Integer.MIN_VALUE/10||(reu==Integer.MIN_VALUE/10&&pop<-8)) return 0;

            reu=reu*10+pop; //將pop壓入到reu後面
        }
        return reu;

    }
}

思路:(官方題解)將輸入的數字從最後一位開始彈出,再將彈出的數字壓入結果數字首位,要注意溢位的問題,如果壓入後的結果大於了int型別最大值或小於了int型別最小值,則返回0;