leetcode: explore-strings-33 反转字符串

时间:2022-07-23
本文章向大家介绍leetcode: explore-strings-33 反转字符串,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

leetcode explore 字符串类第二题:整数反转

题目分析

这里把题目贴出来:

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.

题意拆解:

1、输入:一个整数,可正可负可为0 2、输出:输入值反转,但不包括符号,正数的前置0要省略 3、注意:输入与输出的数值范围都是[−2^31, 2^31 − 1],如果超出,返回0

参考答案

题目的两个难点: 1、符号问题 2、数值范围问题

首先符号问题很好解决,我们在反转字符串之前加个判断就好了。然后就是数值问题,这里有两种解决办法:一种是按字面意思来,我们可以用 math.pow 把边界值计算出来;另外一种则是通过进制运算。参考代码如下:

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        flag = True if x < 0 else False
        s = str(abs(x))
        s = int(s[::-1]) if not flag else -int(s[::-1])
        # if s > (pow(2, 31) - 1) or s < (pow(-2, 31) - 1):
        #     return 0

        v_max = 0xffffffff/2
        if s > (v_max - 1) or s < (v_max*(-1)):
            return 0
        return s


if __name__ == "__main__":
    s = Solution()
    print(s.reverse(123))
    print(s.reverse(-123))
    print(s.reverse(-120))
    print(s.reverse(1534236469))

点击阅读原文可查看题目