【LeetCode-Algorithms】7.Reverse Integer

題目:

Reverse digits of an integer.
Example1: x = 123, return 321Example2: 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.

題目大意:

反轉(zhuǎn)數(shù)字的整數(shù)。
Example1: x = 123,return 321
Example2:x = -123,return -321

解題思路

為防止越界,直接使用long long類型來進行存儲,可以簡化計算。
最終輸出前判斷下是否溢出即可。

具體實現(xiàn)

//1:借用了標準中的INT_MIN和INT_MAX來判斷是否越界
class Solution {
public:
    int reverse(int x) {
        long long lresult = 0;

        while(x)
        {
            lresult = lresult*10 + x%10;
            x /= 10;        
        }

        return (lresult < INT_MIN || lresult > INT_MAX)?0:lresult;
    }
};
// 使用回溯的方式來判斷是否越界
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;
}

你有沒有想過這個?
以下是編碼前要問的一些好問題。如果您已經(jīng)考慮過這一點,很贊!
如果整數(shù)的最后一位是0,輸出應該是多少?即,例如10,100。
你注意到反轉(zhuǎn)的整數(shù)可能會溢出嗎?假設輸入是一個32位整數(shù),則1000000003的倒數(shù)溢出。你應該如何處理這種情況?
為了這個問題的目的,假設當反轉(zhuǎn)的整數(shù)溢出時,你的函數(shù)返回0。

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

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

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