Day 4 – Palindrome Number in JavaScript Without Converting to String
๐ฅ Interview Series – Day 4
๐ก Topic: How to check if a number is a palindrome without converting it to a string in JavaScript
✅ Problem Statement
Check whether a given number is a palindrome without converting it to a string.
A number is a palindrome if it reads the same backward as forward.
๐งช Examples:
121 → true
123 → false
1221 → true
-121 → false (negative numbers are not palindromes)
๐ง JavaScript Code (Math-Based Logic):
function isPalindromeNumber(num) {
if (num < 0) return false;
let original = num;
let reversed = 0;
while (num > 0) {
reversed = reversed * 10 + (num % 10);
num = Math.floor(num / 10);
}
return original === reversed;
}
๐ก Tips to Remember:
Avoid using .toString() — focus on mathematical logic.
% (modulo) gives the last digit.
Math.floor() removes the last digit from the number.
Store the reversed number and compare it to the original.
๐ง๐ป Why Interviewers Ask This:
To test pure logic-building without shortcuts.
To see how well you manage numeric manipulation.
๐ง Alternate Approach (String Method):
function isPalindrome(num) {
if (num < 0) return false;
const str = num.toString();
return str === str.split('').reverse().join('');
}
Use this only if allowed. Real interviews often ban built-in shortcuts!
Comments
Post a Comment