7 - Revere Interger - python

53 阅读1分钟

7.Revere Interger

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.


AC code

import sys
class Solution:
    def reverse(self, x: int) -> int:
        r = []
        flag = 1
        if x < 0:
            flag = -1

        x = abs(x)
        while x:
            r.append(str(x % 10))
            x = x // 10

        if r == []:
            return 0
            
        id = -1
        for i in range(len(r)):
            if int(r[i]) > 0:
                r = r[i:]
                break
        
        x = flag * int(''.join(r))
        return x if -2147483648 < x < 2147483647 else 0
 

或者这样也可以


class Solution:
    def reverse(self, x: int) -> int:
        r = []
        flag = 1
        if x < 0:
            flag = -1
    
        x = abs(x)
        ans = 0
        while x:
            ans = ans * 10 + x % 10
            if -2147483648 < ans < 2147483647:
                x = x // 10
            else:
                return 0
        x = flag * ans 
        return x if -2147483648 < x < 2147483647 else 0