October 6, 2024
We're solving another LeetCode problem today. Tomorrow I will add my new project. Let's dive in.
Today's problem is 9. Palindrome Number. The problem is as follows: Given an integer x, return true if x is a palindrome, and false otherwise.
Example 1: Input: x = 121 Output: true Explanation: 121 reads as 121 from left to right and from right to left. Example 2:
Example 2: Input: x = -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.Write a function that takes the binary representation of a positive integer and returns the number of set bits it has (also known as the Hamming weight).
Let's answer using the UMPIRE method:
1class Solution:2 def isPalindrome(self, x: int) -> bool:3 def recursivePalindrome(s: str) -> bool:4 if len(s) <= 1:5 return True6 elif s[0] != s[-1]:7 return False8 return recursivePalindrome(s[1:-1])910 return recursivePalindrome(str(x))
1def test_isPalindrome(self):2 assert self.test_isPalindrome(1221)3 assert not self.test_isPalindrome(31)
1def isPalindrome(x: int) -> bool:2 s = str(x)3 left = 04 right = len(s) - 15 while left < right:6 if s[left] != s[right]:7 return False8 left += 19 right -= 110 return True
LeetCode as Procrastination
Intro to Cursor