7. Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output:  321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

一刷:
由于不知道輸入的位數(shù),就用while循環(huán)求最低位的數(shù)字,依次降位,然后每次降位再把最低位的和升位:

public static int reverse(int x) {
        int result = 0;
        if (x == 0) {
            return result;
        }
        while (true) {
            int n = x % 10;
            result = result * 10 + n;
            x = (x - n) / 10;
            if (x == 0) {
                break;
            }
        }
        return result;
    }

然而忽略了,反轉(zhuǎn)數(shù)字后越界的問題。
于是考慮在每次賦值的時(shí)候判斷下是否能還原到之前的值,如果可以還原的話就OK了。

public static int reverse(int x) {
        int result = 0;
        if (x == 0) {
            return result;
        }
        while (true) {
            int n = x % 10;
            result = result * 10 + n;
            if (result % 10 != n) {
                return 0;
            }
            System.out.println("result:" + result + ";x:" + x + ";n:" + n);
            x = (x - n) / 10;
            if (x == 0) {
                break;
            }
        }
        return result;
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容