JavaScript

Check if a number is a palindrome in JavaScript

A number is a palindrome if it is written the same way after inverting it.
 
Example:

232, 191, 22022, 111, 666, 12012

 

Program Logic
  • Get the number to check
  • Keep the number in a temporary variable
  • Reverse the number
  • Compare the temporary number with the inverted number
  • If the two numbers are the same, display “the number is a palindrome”
  • Otherwise, display “the number is not a palindrome”
 

Program to check if a number is a palindrome in JavaScript
<!doctype html>
<html>
   <head>
      <script>
         function isPalindrome()
         {
             var tmp=0, x, nbr, y;
			 
             nbr = Number(document.getElementById("MyInput").value);
			 
             y = nbr;
             while(nbr > 0)
             {
               //Compare the first digit with the last digit
               x = nbr%10;
               nbr = parseInt(nbr/10);
               tmp = tmp*10+x;
             }
             //Check whether tmp and y are the same or not.
             if(tmp == y)
             {
                alert("The number is a palindrome.");
             }
             else
             {
                alert("The number is not a palindrome.");
             }
         }
      </script>
   </head>
   <body>
      Enter a number: <input id="MyInput">
      <button onclick="isPalindrome()">Check</button>
   </body>
</html>
Result
Enter a number:
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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