Skip to problem
←

Palindrome Number

Easy 0 attempts

Given an integer x, return true if its ordinary base-10 representation reads the same forwards and backwards; otherwise, return false.

Negative integers are not palindromes because of the minus sign. Zero and every positive single-digit integer are palindromes. Leading zeros are not part of an integer's representation, so 10 is not a palindrome.

Follow-up: Solve this without converting the integer to a string.

Function contract

Implement isPalindrome(x).

Output: Return true if x is a decimal palindrome; otherwise return false.

Example 1

Input
x = 121
Output
true

Example 2

Input
x = -121
Output
false

Example 3

Input
x = 10
Output
false
Constraints
  • -2^31 <= x <= 2^31 - 1
Topics

Reverse Half

Reject negative numbers. Also reject a nonzero number ending in zero: its reverse would need a leading zero.

Move the last digit of x onto rev until the remaining prefix is no larger than the reversed suffix. For an even number of digits, the two halves must be equal. For an odd number, remove the middle digit from rev before comparing. For example, 12321 finishes with x = 12 and rev = 123, so compare 12 with floor(123 / 10).

Only about half the digits are reversed, and no string or digit array is needed. Zero passes because both halves are initially zero.

javascript
function isPalindrome(x) {
  if (x < 0 || (x % 10 === 0 && x !== 0)) return false;
  let rev = 0;
  while (x > rev) {
    rev = rev * 10 + (x % 10);
    x = Math.floor(x / 10);
  }
  return x === rev || x === Math.floor(rev / 10);
}

Time: O(d), where d is the number of decimal digits | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript