LeetCode 练习题(简单2)

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

第一次错误答案:自己的解答直接忽略了负号和溢出的情况,假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231,  231 − 1]。请根据这个假设,如果反转后整       数溢出那么就返回 0。

class Solution(object):
    def reverse(self, x):
        i = x % 10 
        k = x / 100
        j = (x/10)%10
        num = i*100 + j *10 + k return num

 

第二次错误答案:先利用str()函数将整数转化为字符串,然后反转,再利用int()函数将字符串转化为整型,最后判断数值是否溢出。

        x<0时,字符串截取的方法不对

 1 class Solution(object):
 2     def reverse(self, x):
 3         if x >= 0:
 4             reversed_x = int(str(x)[::-1])
 5         else:
 6             reversed_x = int(str(x)[:0:-1])
 7         
 8         if -2**31 < reversed_x <2**31-1:
 9             return reversed_x
10         else:
11             return 0

 注:

Python中字符串切片方法

字符串[开始索引:结束索引:步长]
切取字符串为开始索引到结束索引-1内的字符串
步长不指定时步长为1 字符串[开始索引:结束索引]

一种正确解答:去符号->翻转数字顺序->算出数字->添加符号->判断是否溢出->输出

 1 class Solution:
 2     def reverse(self, x):
 3         result_list = []
 4         i = 0
 5         #判断x的正负,若为负则去掉符号
 6         if x<0:
 7             num = (-1)*x
 8         else:
 9             num = x
10         
11         #将数字翻转
12         while num//10:
13             i += 1
14             result_list.append(num % 10)
15             num = num//10
16         result_list.append(num % 10)
17         i += 1
18         # print(result_list, i)
19         
20         result = 0
21         for j in range(i):
22             result += result_list[j]*pow(10, i-1-j)
23     
24         if x<0:
25             result = result*(-1)
26         if result<=pow(2, 31)-1 and result>=(-1)*pow(2, 31):
27             return result
28         else:
29             return 0   

(注:

  // 为整数的除法;

  pow() 方法返回 xy(x的y次方) 的值。)

猜你喜欢

转载自www.cnblogs.com/dddtz/p/11780900.html