leetcode算法实现之整数反转reverse_integer

-- coding: utf-8 --

如果反转后整数超过 32 位的有符号整数的范围 [−231,  231 − 1] ,就返回 0。

  • 考虑边界
    1.末尾为零的int,反转时删除,末尾连续为0,删至不为0为止
    2.有符号的,符号保持
    3.个位数,直接返回

示例 1:
输入:x = 123
输出:321

示例 2:
输入:x = -123
输出:-321

示例 3:
输入:x = 120
输出:21

示例 4:
输入:x = 0
输出:0
"""

python

def reverse_integer(num):
    """

    :param num: int
    :return: reverse num
    """
    if not isinstance(num, int):
        return False

    num2Str = str(num)
    n = len(num2Str)
    if n == 1 or (n == 2 and num2Str[0] == '-'):
        return num

    def reverse_handle(start, end, numstr):
        stack_ = list()
        for i in range(start, end):
            ch = numstr[i]
            stack_.append(ch)
        newnumstr = ''
        for i in range(start, end):
            newnumstr += stack_.pop()

        count_0 = 0
        for i in range(end-start):
            if i > 0 and newnumstr[i] == '0' and newnumstr[i-1] == '0':
                count_0 += 1
                if newnumstr[i+1] != '0':
                    break
            elif i == 0 and newnumstr[i] == '0':
                count_0 += 1

        newnumstr = newnumstr[count_0:]


        return int(newnumstr)

    if n >= 2:
        if num2Str[0] == '-':
            newnum = reverse_handle(1, n, num2Str)
            return -newnum
        else:
            newnum = reverse_handle(0, n, num2Str)
            return newnum


if __name__ == "__main__":
    num1 = 0
    num2 = -123
    num3 = 120
    num4 = -140
    num5 = 25000
    num6 = -65000
    num7 = -5901010100
    print(reverse_integer(num1))
    print(reverse_integer(num2))
    print(reverse_integer(num3))
    print(reverse_integer(num4))
    print(reverse_integer(num5))
    print(reverse_integer(num6))
    print(reverse_integer(num7))
上一篇:reverse的一些做题教训


下一篇:Unit 22