007 顛倒整數

LeetCode第七題 顛倒整數

給定一個範圍爲 32 位 int 的整數,將其顛倒。
例 1:
輸入: 123
輸出: 321

例 2:
輸入: -123
輸出: -321

例 3:
輸入: 120
輸出: 21

java

    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 = result * 10 + tail;
            x = x / 10;
        }
        return result;
    }

C++

class Solution
{
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;
    }
};

使用python時,有個別測試用例無法通過,跟題目中 “範圍爲32位的int整數”有關,以後可以再研究一下。

python

class Solution(object):
    def reverse(self, x):
        result = 0
        if (x < 0):
            return -Solution().reverse(-x)
        while (x != 0):
            tail = x % 10
            newResult = result * 10 + tail
            if ((int(newResult - tail) / 10) != result):
                return 0
            result = newResult
            x = int(x / 10)
        return result
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章