LeetCode 7. Reverse Integer

Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
將一個整數(shù)中的數(shù)字進行顛倒,當顛倒后的整數(shù)溢出時,返回 0 (標記為 32 位整數(shù))。

分析

通過取余得到最后一位,循環(huán),對于溢出進行判斷即可

代碼

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;
    }
image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容