Leetcode 9. Palindrome Number
Vložit
- čas přidán 5. 05. 2022
- Palindrome Number Leetcode 9,Palindrome Number Leetcode, Leetcode, Palindrome Number, Leetcode Solution, Palindrome Number Leetcode 9 solution, Palindrome Number Leetcode 9 solution java, Palindrome Number solution, Palindrome Number Solution Java,
Connect with me on Facebook : / pratikshabakrola
Subscribe to my channel: / @pratikshabakrola
Java Solution code:
class Solution {
public boolean isPalindrome(int x) {
String xAsString= String.valueOf(x);
int begin_ptr =0;
int end_ptr=xAsString.length()-1;
while(begin_ptr
Another way it can be done is to reverse the input number and then compare the inverted number with the original one. If they're equal then the original number is palindrome. The time complexity is the same as your solution O(n).
+Bogdan Hladiuc , You are absolutely right! If there are alternative solutions for other problems, feel free to add those in the comments as well, it will be helpful for others who reference the comment section!
How does the loop conditional work?
Using the while loop we iterate until we reach middle element. Since we are comparing the first character with last one, second character with second last one, and so on. By the time we reach middle element, we have compared all the characters. When we go pass middle element, condition begin_ptr
Python Solution Code:
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0: return False
div = 1
while x >= 10 * div:
div = div * 10
while x > 0:
right = x % 10
left = x // div
if right != left: return False
x = (x % div) // 10
div = div / 100
return True
Thank you for sharing that !