[LeetCode-07]整數反轉(簡單難度)

題目

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

例子1bash

輸入: 123
輸出: 321

例子2spa

輸入: -123
輸出: -321

例子3code

輸入: 120
輸出: 21

注意io

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

解題

class Solution {
    public int reverse(int x) {
        int result = 0;
        while(x != 0) {
            // 經過與10去餘,獲取x的最後一位數,放到n中
            int n = x % 10;
            // 判斷反轉後的結果是否越界
            if (result > Integer.MAX_VALUE/10 || (result == Integer.MAX_VALUE / 10 && n > 7)) return 0;
            if (result < Integer.MIN_VALUE/10 || (result == Integer.MIN_VALUE / 10 && n < -8)) return 0;
            // result * 10,將result向前進一位,並將n放到result的個位
            // 當result = 0時,進位無效
            result = (result * 10) + n;
            // x = x / 10,小數點向左,x被降一位
            x /= 10;
        }
        return result;
    }
}

經過%10獲取整數x的個位數;時間

經過*10進一位;while

經過/10降一位;co

時間複雜度是O(log(x))數字

空間複雜度是O(1)

相關文章
相關標籤/搜索