From 053ed4a4e6307384f770c8fc6e187ea41b9bbe87 Mon Sep 17 00:00:00 2001 From: mustafanw Date: Sun, 12 Dec 2021 18:02:36 +0530 Subject: [PATCH] Update 007_Reverse_Integer.py This is correct solution. Earlier solution was incorrect. --- python/007_Reverse_Integer.py | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/python/007_Reverse_Integer.py b/python/007_Reverse_Integer.py index a125d47..11c0574 100644 --- a/python/007_Reverse_Integer.py +++ b/python/007_Reverse_Integer.py @@ -27,13 +27,21 @@ class Solution: def reverse(self, x): # Note that in Python -1 / 10 = -1 - res, isPos = 0, 1 - if x < 0: - isPos = -1 - x = -1 * x - while x != 0: - res = res * 10 + x % 10 - if res > 2147483647: - return 0 - x /= 10 - return res * isPos \ No newline at end of file + if x==0: + return 0 + x=str(x) + flag =False + if '-' in x: + flag=True + x=x[::-1] + x=x.replace('-','') + + if flag: + res= int(f'-{x}') + else: + res = int(x) + + if abs(res) < 2**31 and res != 2**31 - 1: + return res + else: + return 0