From 5a52cd9b54553d68ee10cfe87044bed79ee5fb93 Mon Sep 17 00:00:00 2001 From: Yuchen Zhou <72342196+ROMEEZHOU@users.noreply.github.com> Date: Tue, 21 Mar 2023 21:31:55 -0400 Subject: [PATCH] Add a new method for 007_Reverse_Integer.py (#80) * Add a new method for 007 reverse integer Contributed by @ROMEEZHOU --- python/007_Reverse_Integer.py | 39 +++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/python/007_Reverse_Integer.py b/python/007_Reverse_Integer.py index 9f3f20f..19aeba8 100644 --- a/python/007_Reverse_Integer.py +++ b/python/007_Reverse_Integer.py @@ -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 + \ No newline at end of file