Check If A Number Is A Palindrome Without Changing It Into String
I'm having trouble with this problem that simply return True of False if a number n, is a palindrome. Note: wherever I have a ____ indicates where there is a blank that needs to b
Solution 1:
Here's the logic: (y * 10) + x % 10
def is_palindrome(n):
x, y = n, 0
f = lambda: (y * 10) + x % 10
while x > 0:
x, y = x//10 , f()
return y == n
print(is_palindrome(123454321))
# True
print(is_palindrome(12))
# False
y*10
moves the current y to the left by 1 digit, and x%10
adds the last digit.
print(is_palindrome(235))
# False
Pre-iteration: x = 235
, y = 0
First iteration: x = 23
, y = 5
Second iteration: x = 2
, y = 53
Third iteration: x = 0
, y = 532
Solution 2:
Excellent solution, mate! Maybe one little suggestion. Your solution iterates over all n digits, but you have only to iterate n/2 digits. Moreover, you can handle negative values directly because they aren't palindromes.
def is_palindrome(x):
if x < 0 or (x % 10 == 0 and x != 0):
return False
head, tail = x, 0
while head > tail:
head, tail = head // 10, tail * 10 + head % 10
# When the length is an odd number, we can get rid of the middle digit by tail // 10
return head == tail or head == tail // 10
Time complexity: O(log(n)) because we divided 10 in every iteration
Space complexity: O(1)
Post a Comment for "Check If A Number Is A Palindrome Without Changing It Into String"