7. Reverse Integer

來源:互聯網
上載者:User

https://leetcode.com/problems/reverse-integer/description/
題目大意:給一個整數,返回其每位倒序的整數。
解題思路:初始old = 0,每次取整數n的最低位tail,然後從低向高構建新整數new = old * 10 + tail。取得tail後,去掉n的最低位,n=n/10,進入下一輪,直到n=0。
注意為了避免溢出,每次記錄old和new,然後用相反的方法:old = (new-tail)/ 10,判斷old和new是否相等,若前後不相等,說明溢出。

代碼:

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

python實現:基本上與c語言相同,不同在於負數模數和除法需要特別處理,在此簡化為先用正數處理,再轉為負數。此外還需注意判斷是否溢出,因為python的整數類型範圍似乎比c語言要大,因此不用上面的做法判斷溢出,直接檢驗是否在[-2^31, 2^31-1]即可

class Solution:    def reverse(self, x):        """        :type x: int        :rtype: int        """        result = 0        while x != 0:            if x > 0:                  tail = x % 10            else:                tail = -(-x % 10)   #考慮負數處理                     newResult = result * 10 + tail                      if x > 0:                x //= 10            else:                x = -(-x // 10)  #考慮負數處理            result = newResult        if result < 2**31-1 and result > -2**31:            return result        else:            return 0

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.