LeetCode/riteコード-逆Integer-python


質問する



に答える

  • given a signed 32 - bit inger x , return x with its digits reversed.
  • if reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1] , them return 0 .
  • assume the environment does not allow you to store 64-bit integers.
  • コード#コード#

    # leetcode, easy : reverse integer, python3
    # math 
    class Solution:
        def reverse(self, x: int) -> int:
            x = str(x)
            
            if x[0] == '-':
                x = ''.join(list(reversed(x[1:])))
                result = int('-' + x)
            else:
                result = int(''.join(list(reversed(x))))
                
            if result > 2**31 - 1 or result < -2**31:
                return 0
                
            return int(result)

    結果





    ソース&ハーブ


    LeetCode
    github