How to usefor Loop and Math.floor() Method in Javascript
In 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;
temp = Math.floor(temp / 10)) {
reversed = reversed * 10 + temp % 10;
};
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.
function palindromeCheck(number) {
if (number < 0) {
return false;
}
let original = number;
let reversed = 0;
for (let temp = original; temp > 0;
temp = Math.floor(temp / 10)) {
reversed = reversed * 10 + temp % 10;
}
return number === reversed;
}
console.log(palindromeCheck(121));
console.log(palindromeCheck(12321));
console.log(palindromeCheck(12345));
Output
true true false
JavaScript Program to Check for Palindrome Number
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
Output : Palindrome
Input : Number = 1331
Output : Palindrome
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
- Approach 1: Using String Reversal
- Approach 2: Using Array Every() Method
- Approach 3: Using XOR Operator
- Approach 4: Using for Loop and Math.floor() Method
- Approach 5: Using Recursion
We will explore all the above methods along with their basic implementation with the help of examples.