Write a program to check a number is palindrome or not?
What is palindrome?
A palindrome is a sequence of numbers or letters that match if we read from left to right and from right to left.
When we reverse a number or a string, if the reserved number or string is equal to the original number or string, it is called a palindrome.
Examples of palindrome number or string:
Examples of palindrome number or string: 12321, madam, etc.
Example of palindrome function:
Write an isPalindrome function without converting the integer to a string.
function isPalindrome(num) { if (num < 0) return false; let result = 0; let originalNum = num; while (1) { const rem = num % 10; num = parseInt(num / 10); result = result * 10 + rem; if (num < 1) break; } return originalNum === result; } console.log(isPalindrome(1004006004001));
Palindrome algorithm steps with string:
- Get a string or number from the user.
- Take a temporary variable that contains numbers.
- Reverse the given number.
- Compare the original number and reversed number.
- If the temporary and the original number are the same, then the number or string is a palindrome.
- Otherwise, the given string or number is not a palindrome.
Example:
function checkPalindrome(str) { // convert string to an array const array = string.split(''); // reverse the array values const reverseValues = array.reverse(); // convert array to string const reverseString = reverseValues.join(''); if(string === reverseString) { console.log('This is a palindrome'); } else { console.log('This is not a palindrome'); } } //take input const string = prompt('Enter a string: '); checkPalindrome(string);
Palindrome algorithm with string:
const isPalindrome = (s) => { let i = 0; let j = s.length - 1; while (i < j) { if (s[i] === s[j]) { i++; j--; } else { return false; } } return true; } console.log(isPalindrome('aaba')); // true