-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquestion_2.py
More file actions
57 lines (48 loc) · 1.1 KB
/
question_2.py
File metadata and controls
57 lines (48 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/5/3 10:07
# @Author : cancan
# @File : question_2.py
# @Function : 颠倒整数
"""
Question:
给定一个 32 位有符号整数,将整数中的数字进行反转。
Example 1:
输入: 123
输出: 321
Example 2:
输入: -123
输出: -321
Example 3:
输入: 120
输出: 21
Note:
假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。
根据这个假设,如果反转后的整数溢出,则返回 0。
"""
class Solution1:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
f = lambda x: x if -2 ** 31 <= x <= 2 ** 31 - 1 else 0
if x > 0:
return f(int(str(x)[::-1]))
elif x < 0:
return f(int('-' + str(x)[1:][::-1]))
else:
return x
class Solution2:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
r = int(str(abs(x))[::-1])
if r > 2**31:
return 0
if x < 0:
return -r
else:
return r