leetcode 7. Reverse Integer
2018-03-15 13:07
519 查看
本题要考虑边界条件32bit有符号int最大值为2^31-1,最小为-2^31,整数反转思想如下代码
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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Solution
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
y = 0
flag = True
if x < 0:
flag = False
x = abs(x)
max_v = 2**31 -1
max_neg_v = 2**31
while x != 0:
y = y * 10 + x % 10
x = int(x / 10)
if flag and y > max_v:
return 0
elif not flag and y > max_neg_v:
return 0
if flag:
return y
else:
return -y
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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Solution
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
y = 0
flag = True
if x < 0:
flag = False
x = abs(x)
max_v = 2**31 -1
max_neg_v = 2**31
while x != 0:
y = y * 10 + x % 10
x = int(x / 10)
if flag and y > max_v:
return 0
elif not flag and y > max_neg_v:
return 0
if flag:
return y
else:
return -y
相关文章推荐
- LeetCode - 7. Reverse Integer
- 蜗牛慢慢爬 LeetCode 7. Reverse Integer [Difficulty: Easy]
- LeetCode 7. Reverse Integer
- 【LeetCode】7. Reverse Integer
- LeetCode 7. Reverse Integer(数学)
- 【LeetCode】7. Reverse Integer
- LeetCode 7. Reverse Integer (倒转数字)
- Leetcode:7. Reverse Integer
- 【leetcode】7. Reverse Integer(Python & C++)
- leetcode 7. Reverse Integer
- LeetCode7. Reverse Integer
- [LeetCode]7. Reverse Integer
- LeetCode 7. Reverse Integer
- 【leetcode】7. Reverse Integer
- LeetCode 7. Reverse Integer 关于溢出很好的理解和处理
- leetcode7. Reverse Integer
- [LeetCode]7. Reverse Integer&190. Reverse Bits
- LeetCode题解--7. Reverse Integer
- leetcode:7. Reverse Integer
- Leetcode 7. Reverse Integer(java版)