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.
將一個(gè)整數(shù)中的數(shù)字進(jìn)行顛倒,當(dāng)顛倒后的整數(shù)溢出時(shí),返回 0 (標(biāo)記為 32 位整數(shù))。

分析

通過取余得到最后一位,循環(huán),對于溢出進(jì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)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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