• 反转整数


    反转整数

    给定一个 32 位有符号整数,将整数中的数字进行反转。

    示例 1:

    输入: 123
    输出: 321
    

     示例 2:

    输入: -123
    输出: -321
    

    示例 3:

    输入: 120
    输出: 21
    

    注意:

    假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−2**31,  2**31 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。

     1 class Solution:
     2     def reverse(self, x):
     3         """
     4         :type x: int
     5         :rtype: int
     6         """
     7         y = 0
     8         flag = 0
     9         if x < 0:
    10             x = -1 * x
    11             flag = 1
    12         while x/10:
    13             y = y*10 + x%10
    14             x = x//10
    15         if flag == 1:
    16             y = -1*y
    17         if y < pow(-2, 31) or y > pow(2, 31) - 1:
    18             return 0
    19         return y

    代码简化:

     1 class Solution:
     2     def reverse(self, x):
     3         """
     4         :type x: int
     5         :rtype: int
     6         """
     7         res = int(str(x)[::-1]) if x > 0 else -int(str(x).lstrip('-')[::-1])
     8         return res if -2 ** 31 <= res <= 2 ** 31-1 else 0

    1.  lstrip()

    Python lstrip() 方法用于截掉字符串左边的空格或指定字符。

    2.  [::-1]

    用于取反向字符串

    3.  注意if else 的结构

  • 相关阅读:
    NodeJS优缺点及适用场景讨论
    gitHub安装步骤
    ubuntu16.04爬坑
    Dubbo入门
    oracle11g的卸载
    数据库对象的创建和管理
    oracle数据库中的面试题
    dml数据操作和tcl事务管理
    oracle sql单行函数 常用函数实例
    oracle查询语句汇总与分类
  • 原文地址:https://www.cnblogs.com/yxh-amysear/p/9291585.html
Copyright © 2020-2023  润新知