Palindrome Number
LeetCode 9 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
Reverse half the digits and compare.
मी Palindrome Number (LeetCode 9) असा सोडवला — Other पॅटर्नमधील एक सोपा प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.
खालील विवरण इंग्रजीत आहे.
Intuition
Reverse only the second half of the number and compare it with the first half. Stop when the reversed part is no longer smaller than what's left; for odd lengths, drop the middle digit with // 10.
Approach
- 1
Negatives and numbers ending in 0 (except 0) aren't palindromes.
- 2
Move digits from x onto reversed until reversed ≥ x.
- 3
Compare x with reversed or reversed // 10.
मी कसा सोडवला
Half reversalPythonO(log x) time
class Solution:
def isPalindrome(self, x: int) -> bool:
if x<0 or (x!=0 and x%10==0):
return False
#121
#reverse from right till middle is same return true
reversed = 0
while x>reversed:
reversed = reversed*10+x%10
x = x//10
return True if reversed == x or reversed//10 == x else False
#12321 12, 12, for odd length revesrsed will be 123, so if we devide 123/10 we will get 12Palindrome Number — वारंवार विचारले जाणारे प्रश्न
Palindrome Number मागील intuition काय आहे?
Reverse only the second half of the number and compare it with the first half. Stop when the reversed part is no longer smaller than what's left; for odd lengths, drop the middle digit with // 10.
Palindrome Number (LeetCode 9) कसा सोडवावा?
1. Negatives and numbers ending in 0 (except 0) aren't palindromes. 2. Move digits from x onto reversed until reversed ≥ x. 3. Compare x with reversed or reversed // 10.
Palindrome Number ची time आणि space complexity किती आहे?
Time: O(log x). Space: O(1). (Accepted approach: Half reversal.)
Palindrome Number मध्ये सामान्य चुका कोणत्या?
Converting to a string works but isn't the intended trick.