【Leetcode】7. 整數反轉(Reverse Integer)

Leetcode - 7 Reverse Integer (Easy)

題目描述:反轉一個 32 位有符號的整數。

Input: -123
Output: -321

解題思路:注意整型範圍越界。

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 /= 10;
    }
    return result;
}
發佈了212 篇原創文章 · 獲贊 43 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章