logo
logo

Palindrome Number

Lesson

Write a function to determine whether a given integer is a palindrome without converting it to a string. A palindrome means that the integer can be read forwards and backwards the same way. The function should return true if the integer is a palindrome, otherwise false.

Input: 1001
Output: true

Input: 3923
Output: false

Walkthrough

To solve the problem, we will first check if the number is negative because negative numbers cannot be palindromes. Then, we will create a variable called "reverse" to store the reversed integer. To get the reversed integer, we will loop through the input number and get its last digit using the modulo operator. We will then append the last digit to the "reverse" variable and remove it from the input number by dividing it by 10 and truncating the last decimal using the bitwise OR operator with 0. We will repeat this process until the input number becomes 0. After that, we will compare the input number with the "reverse" variable. If they are equal, the number is a palindrome and we return true. Otherwise, the number is not a palindrome and we return false.

Here is the code to implement the solution

function isPalindrome(number) {
  if (number < 0) {
    return false;
  }
  let reverse = 0;
  let copy = number;
  while (copy > 0) {
    const lastDigit = copy % 10;
    reverse = reverse * 10 + lastDigit;
    copy = (copy / 10) | 0;
  }
  return number === reverse;
}

Big O Complexity Analysis: The time complexity of this solution is O(log n) because we loop through the input number and divide it by 10 each time, which reduces the size of the input number by a factor of 10. Therefore, the number of iterations required is proportional to the number of digits in the input number, which is log base 10 of the input number. The space complexity of this solution is O(1) because we only use a constant amount of extra space to store the reverse and copy variables.

Note that using the bitwise OR operator to truncate the last decimal is a trick that works in JavaScript, but may not work in other programming languages. In other languages, you may need to use a different approach to truncate the decimal.