LeetCode:7. Reverse Integer

题目:
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: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Answer:

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        sum = 0
        n = 0
        if x > 0:
            flag = 1
        else:
            flag = -1
        x = x * flag
        lt = []
        while x:
            lt.append(x % 10)
            x = int(x / 10)
            n += 1
        for i in lt:
            sum += i * pow(10, n-1)
            n -= 1

        if sum > pow(2, 31) - 1 or sum < -pow(2, 31):
            return 0

        if flag == -1:
            return -sum
        else:
            return sum

思路:
将数字拆开存入数组中,再组合成Reverse Interger,注意数字范围,最后加上正负判断。
这里写图片描述

发布了43 篇原创文章 · 获赞 27 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/SCUTJcfeng/article/details/80006713
今日推荐