Reverse Integer - Python Solution&Explanation

  • 0

    [My Thoughts..]

    Given x is number and type is 'integer'.

    1. Make x to string and reverse it. Make it to a number. Define it as 'r' (r is a result) .

    • Question1: if x<0 ?
      For example, if x is -120 and reverse it, it becomes '021-'.

    • Answer1: If x<0, use abs(), reverse it and make it to a number and add ' - ' in front of it.

    • Question2: How to convert '021' to an integer? Does it start with '0'?
    • Answer2:
                 >>> int('021')

    2. "Note" says, "integer within the 32-bit signed integer range" : Judge the length of binary number of 'r' whether it is in range of 0 ~ 31

    • Question1: If r<0 (r is a reversed integer) and convert it, for example, ' -11 ' will be ' 11- '.
    • Answer1: Use abs() and make it to a binary number.

    • Question2: Using bin(), it will start with '0b'.
    • Answer2: We don't need '0b'. Therefore, len(bin(abs(r))) - 2

    3. If it is in range of 0~31, return 'r'.
        If it is not in range of 0~31, return 0

    [My Solution is..]

    class Solution:
        def reverse(self, x):
            if x<0:
            if len(bin(abs(r)))-2 in range(32):
                return r
                return 0    

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.