Skip to content

Commit badcfc4

Browse files
committed
updated 0009_palindrome_number.py
1 parent f9cd869 commit badcfc4

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

problems/easy/0009_palindrome_number.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,20 +26,25 @@
2626
-2^31 <= x <= 2^31 - 1
2727
"""
2828
class Solution:
29-
# First approach, complexity O(n)
29+
# First approach, complexity O(n) and using string conversion
3030
#def isPalindrome(self, x: int) -> bool:
3131
# x = str(x)
3232
# return x == x[::-1]
33+
3334
# Enough to revers half of digits and compare them
3435
# to the other half. Complexity log(x)
3536
def isPalindrome(self, x: int) -> bool:
36-
if (x < 0) or (x % 10 == 0 and x != 0):
37+
if x < 0 or (x % 10 == 0 and x != 0):
3738
return False
38-
39-
reversed = 0
40-
while(x > reversed):
41-
reversed = reversed * 10 + x % 10
39+
40+
if x >= 0 and x < 10:
41+
return True
42+
43+
p = 0
44+
while x > 0:
45+
p = (10 * p) + x % 10
46+
if (p == x) or (p == x // 10):
47+
return True
4248
x = x // 10
4349

44-
# reversed // 10 -> for numbers with odd number of digits
45-
return (x == reversed) or (x == reversed // 10)
50+
return False

0 commit comments

Comments
 (0)