
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Verify if a Number is Palindrome in JavaScript
Let’s say, we have to write a function that takes in a Number and returns a boolean based on the fact whether or not the number is palindrome. One restriction is that we have to do this without converting the number into a string or any other data type.
Palindrome numbers are those numbers which read the same from both backward and forward.
For example −
121 343 12321
Therefore, let’s write the code for this function −
Example
const isPalindrome = (num) => { // Finding the appropriate factor to extract the first digit let factor = 1; while (num / factor >= 10){ factor *= 10; } while (num) { let first = Math.floor(num / factor); let last = num % 10; // If first and last digit not same return false if (first != last){ return false; } // Removing the first and last digit from number num = Math.floor((num % factor) / 10); // Reducing factor by a factor of 2 as 2 digits are dropped factor = factor / 100; } return true; }; console.log(isPalindrome(123241)); console.log(isPalindrome(12321)); console.log(isPalindrome(145232541)); console.log(isPalindrome(1231));
Output
The output in the console will be −
false true true false
Advertisements