Skip to content

Commit

Permalink
Add a new method for 007_Reverse_Integer.py (#80)
Browse files Browse the repository at this point in the history
* Add a new method for 007 reverse integer

Contributed by @ROMEEZHOU
  • Loading branch information
ROMEEZHOU authored Mar 22, 2023
1 parent 92c80f9 commit 5a52cd9
Showing 1 changed file with 28 additions and 11 deletions.
39 changes: 28 additions & 11 deletions python/007_Reverse_Integer.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,34 @@
class Solution:
def reverse(self, x):
# https://leetcode.com/problems/reverse-integer/
flag = True if x < 0 else False
if flag:
# flag = True if x < 0 else False
# if flag:
# x = -x
# x = str(x)[::-1]

# if flag:
# x = "-" + x

# value = 2 ** 31
# x = int(x)
# if -value <= x < value:
# return x
# return 0

is_neg = False
if x < 0:
x = -x
x = str(x)[::-1]
is_neg = True

if flag:
x = "-" + x
res = 0
while x > 0:
res *= 10
res += x % 10
x //= 10
if is_neg:
res = -res

value = 2 ** 31
x = int(x)
if -value <= x < value:
return x
return 0

if res < -2**31 or res > 2**31-1:
return 0
return res

0 comments on commit 5a52cd9

Please sign in to comment.