[LeetCode][Python]7. Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Have you thought about this?Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

解題思路:

  1. python里面int最大數值0x7FFFFFFF,在考慮溢出的時候需要和這個值進行比較。

  2. 取模運算可以得到數字的最后一位,/運算會得到移走最后一個數字之外的數字,以此循環

    代碼如下:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        res = 0
        flag = -1 if x<0 else 1
        x = x * flag

        while(x):
            res = res*10 + x%10
            x = x/10
        if res > 0x7FFFFFFF:
            return 0
        return res*flag

if __name__ == "__main__":
    sol = Solution()
    print sol.reverse(123)
    print sol.reverse(1000)
    print sol.reverse(10001)
    print sol.reverse(-123)
    print sol.reverse(1000000003)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,779評論 0 33
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,552評論 5 6
  • 這兩天通過學習,我決定改變和女兒的惡劣關系。從上初中起女兒愛上打扮,每天都要化妝,為這事沖突不斷,我覺的這個年齡應...
    可樂開心閱讀 619評論 2 4
  • 靜靜地坐在教室里,兩眼環視著教室,偌大的教室只有4個人而已,心中不免多了一絲擔憂與迷茫,其他同學去畫室上美術課了,...
    xiao嫣閱讀 422評論 0 1
  • 離開了,我才開始重視自己。我會努力變得更好的。你有一只粉色豬豬。好在我還有一只藍色的。 中秋佳節,忍不住跑回家吃中...
    豬悟能閱讀 208評論 0 0