Palindrome Number in Javascript

nikhilkalariya

nikhilkalariya

Posted on July 21, 2024

Palindrome Number in Javascript

Method 1: String Conversion and Reversal

function isPalindrome(number) {
    const str = number.toString();
    const reversedStr = str.split('').reverse().join('');
    return str === reversedStr;
}

// Example usage
console.log(isPalindrome(121)); // true
console.log(isPalindrome(123)); // false
console.log(isPalindrome(1331)); // true

Enter fullscreen mode Exit fullscreen mode

Method 2: Using a Loop


function isPalindrome(number) {
    const str = number.toString();
    const len = str.length;

    for (let i = 0; i < len / 2; i++) {
        if (str[i] !== str[len - 1 - i]) {
            return false;
        }
    }
    return true;
}

// Example usage
console.log(isPalindrome(121)); // true
console.log(isPalindrome(123)); // false
console.log(isPalindrome(1331)); // true

Enter fullscreen mode Exit fullscreen mode

Method 3: Mathematical Approach
This approach avoids string conversion and operates directly on the number.


function isPalindrome(number) {
    if (number < 0) return false; // Negative numbers are not palindromes
    let reversed = 0;
    let original = number;

    while (original > 0) {
        const digit = original % 10;
        reversed = reversed * 10 + digit;
        original = Math.floor(original / 10);
    }

    return number === reversed;
}

// Example usage
console.log(isPalindrome(121)); // true
console.log(isPalindrome(123)); // false
console.log(isPalindrome(1331)); // true
Enter fullscreen mode Exit fullscreen mode

Method 4: Using Recursion

function isPalindromeHelper(str, start, end) {
    if (start >= end) return true;
    if (str[start] !== str[end]) return false;
    return isPalindromeHelper(str, start + 1, end - 1);
}

function isPalindrome(number) {
    const str = number.toString();
    return isPalindromeHelper(str, 0, str.length - 1);
}

// Example usage
console.log(isPalindrome(121)); // true
console.log(isPalindrome(123)); // false
console.log(isPalindrome(1331)); // true
Enter fullscreen mode Exit fullscreen mode

Method 5: Using Regular Expressions

function isPalindrome(number) {
    const str = number.toString();
    const reversedStr = str.replace(/[\W_]/g, '').split('').reverse().join('');
    return str === reversedStr;
}

// Example usage
console.log(isPalindrome(121)); // true
console.log(isPalindrome(123)); // false
console.log(isPalindrome(1331)); // true

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
nikhilkalariya
nikhilkalariya

Posted on July 21, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related