palindrome number leetcode solution jsdiet.com
Question 9. Palindrome Number – Leetcode Javascript Solution
Difficulty Easy
Question Type String
Question Link https://leetcode.com/problems/palindrome-number/

Problem Description :

Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward.

For example, 121 is a palindrome while 123 is not.

Example 1:

 Input: x = 121 
 Output: true
 Explanation: 121 reads as 121 from left to right and from right to left

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.

Example 3:

 Input: x = 10  
 Output: false  
 Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Constraints:

  -231 <= x <= 231 - 1

Solution 1 (Using Native String and Array) :

var isPalindrome = function (x) {
    if(x < 0) return false;
    const tmp = parseInt(x.toString().split('').reverse().join(''))
    return x === tmp;
};

// To run Program
console.log(isPalindrome(121));

Complexity Analysis :

    Time complexity: O(n)
    Space complexity: O(1)

Solution 2 ( Quicksort ) : ==> Optimized

let’s think about how to revert the last half of the number. For number 1221, if we do 1221 % 10, we get the last digit 1, to get the second to the last digit, we need to remove the last digit from 1221, we could do so by dividing it by 10, 1221 / 10 = 122. Then we can get the last digit again by doing a modulus by 10, 122 % 10 = 2, and if we multiply the last digit by 10 and add the second last digit, 1 * 10 + 2 = 12, it gives us the reverted number we want. Continuing this process would give us the reverted number with more digits.

var isPalindrome = function(x) {
    if(x < 0 ) return false;       // Only Positive Number to allow
    if(x < 10)  return true;       // for 1-9 single digit cases
    if(x %10 === 0) return false;  // incase of last value 0 [220, 330]
    
    let reverse = 0;
    while(reverse < x){
        reverse = (reverse * 10) + (x % 10);
        x = Math.trunc(x/10);     // Math.trunc to avoid float values
    }
    return (x === reverse) || (Math.trunc(reverse/10) === x);
};

// To run Program
console.log(isPalindrome(1221));

Complexity Analysis :

    Time complexity: O(log10(n)) 
    Space complexity: O(1)

Since we divided the number by 10, and multiplied the reversed number by 10, when the original number is less than the reversed number, it means we’ve processed half of the number digits. So the time complexity is O(log10​(n))

If you have any doubts, add in comment section. Will clarify at my level best. Also, if you have better solution, kindly share it, will grow together as to become better engineer.

By Gopi M

Leave a Reply

Your email address will not be published. Required fields are marked *