-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a new method for 007_Reverse_Integer.py (#80)
* Add a new method for 007 reverse integer Contributed by @ROMEEZHOU
- Loading branch information
Showing
1 changed file
with
28 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|