File tree Expand file tree Collapse file tree 1 file changed +13
-8
lines changed Expand file tree Collapse file tree 1 file changed +13
-8
lines changed Original file line number Diff line number Diff line change 26
26
-2^31 <= x <= 2^31 - 1
27
27
"""
28
28
class Solution :
29
- # First approach, complexity O(n)
29
+ # First approach, complexity O(n) and using string conversion
30
30
#def isPalindrome(self, x: int) -> bool:
31
31
# x = str(x)
32
32
# return x == x[::-1]
33
+
33
34
# Enough to revers half of digits and compare them
34
35
# to the other half. Complexity log(x)
35
36
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 ):
37
38
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
42
48
x = x // 10
43
49
44
- # reversed // 10 -> for numbers with odd number of digits
45
- return (x == reversed ) or (x == reversed // 10 )
50
+ return False
You can’t perform that action at this time.
0 commit comments