[LeetCode]#7.Reverse Integer

Fatboy Slim
1 min readMar 29, 2020

--

Environment: Python 3.7

Key technique: Slice, 32 bit number binary

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Analysis:

  1. Use slice to get reverse number
  2. if the number is negative, Multiply it *-1.
  3. Don’t let number exceed 32 bit number.

Solution:

class Solution:
def reverse(self, x):
if x>=0:
ans=int(str(x)[::-1])
else:
x=x *-1
ans=int(str(x)[::-1])*-1
if ans>2147483647 or ans<-2147483648:
ans=0
return ans

Submitted result:

Lesson learn:

The video maximum damage or hp is 2147483647 due to the 32 bit limit.

Reference:

http://www.padpadblog.com/2019/05/2147483647.html?fbclid=IwAR1Y4K_hIbzAJGj_cZYCsIY8eTVBRyWtLZ63FLxD2_kpwtN3a431pptfDhg

https://www.itread01.com/p/521344.html

--

--

Fatboy Slim
Fatboy Slim

Written by Fatboy Slim

Interesting in any computer science.

No responses yet