7. Reverse Integer (Easy)

Description:

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.


My Solution (w/ notes in comments):

Solution1: reverse string

class Solution:
    def reverse(self, x: int) -> int:
        sign = 1
        if x < 0:
            sign = -1
        x = abs(x)
        string = str(x)[::-1]
        result = int(string)*sign
        if result > pow(2,31)-1 or result < -pow(2,31):
            return 0 # cautious for the overflow case!!!
        else:
            return result

Performance:

  • Runtime: 36 ms, faster than 91.11% of Python3 online submissions for Reverse Integer.
  • Memory Usage: 13.2 MB, less than 69.12% of Python3 online submissions for Reverse Integer.

Solution2: mod

        sign = 1
        if x < 0:
            sign = -1
        x = abs(x)
        result = 0
        length = len(str(x))
        while length > 0:
            result += x%10 * pow(10,length-1)
            x = (x-x%10)/10
            length -= 1
        if result > pow(2,31)-1 or result < -pow(2,31):
            return 0
        else:
            return int(result)*sign # cautious for the type of result. It's double!!

Performance:

  • Runtime: 36 ms, faster than 91.11% of Python3 online submissions for Reverse Integer.
  • Memory Usage: 13.5 MB, less than 5.00% of Python3 online submissions for Reverse Integer.

你可能感兴趣的:(7. Reverse Integer (Easy))