zoukankan      html  css  js  c++  java
  • 【LeetCode每天一题】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: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

    思路:对于负数设置一个标志位,然后将其转化成正整数,再来计算,最后判断大小是否超过了[−231,  231 − 1]这个范围。时间复杂度为O(log 10 x), 空间复杂度为O(1)。

    代码


     1 class Solution(object):
     2     def reverse(self, x):
     3         """
     4         :type x: int
     5         :rtype: int
     6         """
     7         if x == 0:                     # 为0直接返回
     8             return 0
     9         res, neg_flag = 0,False         # 设置结果和负数标志位
    10         if x < 0:
    11             neg_flag = True
    12             x = abs(x)
    13         while x:                      # 进行反转
    14             tem = x % 10
    15             x = x// 10
    16             res = (res*10 + tem)  
    17         if neg_flag:                   # 判断舒服标志位,并进行相应的转换
    18             res =  0-res
    19         if res > pow(2,31)-1 or res < -pow(2,31):      # 判断是否超出范围, 直接返回0
    20             return 0
    21         return res                  # 返回结果
  • 相关阅读:
    codesmith+mysql生成代码
    遭遇笔试
    线性是一种简洁,简洁就是美
    Microsoft Kinect SDK vs PrimeSense OpenNI
    资料收集:让OpenCV使用IPP
    提纲
    在PC上安装使用Kinect
    OpenNI设置Kinect帧率,读取IR图
    cout,rather than printf
    单步调试时,getnextframe会失败。又
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10635519.html
Copyright © 2011-2022 走看看