7. Reverse Integer

Two things to consider about when dealing with number operations, number sign and overflow

def solve(num):
    MAX, MIN = 65535, -65536
    if num == MIN:
        return 0
    abs_num = -num if num < 0 else num
    ans = 0
    while abs_num > 0:
        if ans > (MAX - abs_num % 10) / 10:
            return 0
        ans = ans * 10 + abs_num % 10
        abs_num /= 10
    return -ans if num < 0 else ans


print solve(65537)

 

posted @ 2018-08-17 20:56  geeklove  阅读(73)  评论(0)    收藏  举报