Skip to content

Latest commit

 

History

History
42 lines (38 loc) · 928 Bytes

7.md

File metadata and controls

42 lines (38 loc) · 928 Bytes

题目地址

https://leetcode-cn.com/problems/reverse-integer/

解答1

def reverse(x):
    """ 整数反转 """
    if x == 0:
        return 0
    str_x = str(x)
    if str_x[0] == "-":
        rev = int("-" + str_x[len(str_x) - 1::-1].lstrip("0").rstrip("-"))
    else:
        rev = int(str_x[len(str_x) - 1::-1].lstrip("0"))
    if rev < -2 ** 31 or rev > 2 ** 31 - 1:
        return 0
    return rev

解答2

def reverse(x):
    """ 整数反转 """
    rev, temp = 0, 0
    max_v = 2 ** 31 - 1
    min_v = -2 ** 31

    while x != 0:
        if x < 0:
            pop = -(-x % 10)
            x = -(-x // 10)
        else:
            pop = x % 10
            x //= 10
        if rev > max_v // 10 or rev == max_v // 10 and pop > 7:
            return 0
        if rev < -(-min_v // 10) or rev == -(-min_v // 10) and pop < -8:
            return 0
        rev = rev * 10 + pop

    return rev