7. Reverse Integer

題目鏈接
tag:

  • easy

question:
??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

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: -2147483648~2147483647. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

C++ 解法:
思路:
??用long long型變量保存計算結(jié)果,最后返回的時候判斷是否在int返回內(nèi),代碼如下:

class Solution {
public:
    int reverse(int x) {
        // 數(shù)學(xué)分析不等式條件
        int res = 0;
        while (x != 0) {
            if (res > INT_MAX / 10 || res < INT_MIN / 10) {
                return 0;
            }
            int digit = x % 10;
            x /= 10;
            res = res*10 + digit;
        }
        return res;
    }
};
class Solution {
public:
    int reverse(int x) {
        long long res = 0;
        while (x != 0) {
            res = res*10 + x % 10;
            x /= 10;
        }
        return (res < INT_MIN || res > INT_MAX) ? 0 : res;
    }
};

Python 解法:
??比較簡單,轉(zhuǎn)化為字符串反轉(zhuǎn)即可,見代碼:

class Solution:
    def reverse(self, x: int) -> int:
        res = int(str(abs(x))[::-1])
        if res > 2**31-1:
            return 0
        if x < 0:
            return -res
        else:
            return res
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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