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

Popular posts from this blog

Day 9 – Count Vowels in a String using JavaScript | DSA Challenge with Code & Explanation

Day 13: Find Missing Number in an Array – JavaScript DSA Challenge