![]() |
We are going to learn about Palindrome Numbers in JavaScript. A palindrome number is a numerical sequence that reads the same forwards and backward, It remains unchanged even when reversed, retaining its original identity. Example: Input : Number = 121 There are several methods that can be used to check if a number is a Palindrome Number in JavaScript, which are listed below: Table of Content We will explore all the above methods along with their basic implementation with the help of examples. Approach 1: Using String ReversalIn this approach, we Convert the number to a string. Reverse the string and compare it with the original. Return true if equal, indicating a palindrome; otherwise, false. Syntax: let result = numStr.split('').reverse().join(''); Example: In this example we are using the above-explained approach.
Output true false Approach 2: Using Array Every() MethodIn this approach, we convert number to string, and split it into array. Check if each digit matches its counterpart in reverse order using the every method for palindrome detection. Syntax: every((element, index, array) => { /* … */ }) Example: In this example, the number is converted to a string, and then that string is split into an array of characters. The every method is used to check if every digit in the array matches its counterpart in the reversed position
Output true true false Approach 3: Using XOR OperatorIn this approach, we convert number to string. Use XOR on ASCII values of corresponding characters, checking palindrome property. Return boolean value for palindrome detection. Syntax: a ^ b Example:
Output true true false Approach 4: Using for Loop and Math.floor() MethodIn this approach, we are using Math.floor method, reverse the number iteratively. Compare reversed number with original for palindrome check. Exclude negatives. Syntax: for (let temp = original; temp > 0; Example: In this example, the palindromeCheck function uses a for loop to reverse positive numbers. It compares the reversed and original numbers, returning true for palindromes and false otherwise.
Output true true false Approach 5: Using RecursionIn this approach, we convert the number to a string. We then use a recursive function to check if the first and last characters of the string are the same, gradually moving towards the center of the string. If they match, the function continues checking the next pair of characters until all pairs are checked. If they don’t match, it returns false. Example: In this example, the ‘palindromeCheck‘ function converts the number to a string and calls the recursive function isPalindrome with the starting and ending indices of the string.
Output true true false true
|
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |