leetcode刷题-----7. 整数反转

栏目: 编程工具 · 发布时间: 6年前

内容简介:假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。来源:力扣(LeetCode)链接:

题目:

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

  • 示例 1:

    输入: 123

    输出: 321

  • 示例 2:

    输入: -123

    输出: -321

  • 示例 3:

    输入: 120

    输出: 21

注意:

假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

来源:力扣(LeetCode)

链接: https://leetcode-cn.com/probl...

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解答:

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        max0 = 2**31-1
        min0 = -(2**31)
        symbol = True
        if x > max0 or x < min0:
            return 0
        if x < 0:
            symbol = False
            x = -x
        int_x = str(x)
        raw = int_x[::-1]
        raw = int(raw)
        if raw > max0:
            return 0
        if not symbol:
            return -raw
        return raw

关键:

  1. 将整数转换为字符串进行切片反转
  2. 注意溢出
  3. 注意符号

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Creative Selection

Creative Selection

Ken Kocienda / St. Martin's Press / 2018-9-4 / USD 28.99

Hundreds of millions of people use Apple products every day; several thousand work on Apple's campus in Cupertino, California; but only a handful sit at the drawing board. Creative Selection recounts ......一起来看看 《Creative Selection》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具