Palindrome Number

Pattern: Maths basics

easy

Decide whether a whole number reads the same from both ends, by reversing only its second half.

The problem

You are given a 32-bit integer x, which may be negative. Return true if its decimal digits read the same from left to right as from right to left, and false otherwise. For example, 121 and 12321 are palindromes, 10 is not, and -121 is not, because "-121" backwards is "121-".

The function name isPalindrome matches LeetCode. Use the link above for the exact statement. LeetCode also asks you to try it without turning the number into text, and that is the version this guide builds.

Think first

Work with 1221 and 12321 on paper.

  • What happens to a negative number when you read it backwards?
  • You already know how to peel the last digit off a number. If you glue the peeled digits together into a new number, what do you get?
  • Do you really need the whole reversed number, or only part of it?

Hints

    Brute force, and why it fails

    Turn the number into text and compare the text with its reverse. That is correct, short and fast, because a 32-bit number has at most 10 digits. Another option is to reverse the whole number into a 64-bit variable and compare.

    Both are fine for a quick answer. This guide goes further because the problem asks for a version without text, and because reversing only half avoids overflow without needing a bigger type. That half-reversal is a neat trick that comes up again.

    The key insight

    A palindrome's second half, reversed, equals its first half. Move digits from the end of x onto half until half is at least as big as what remains of x. Then compare x with half (even length) or with half / 10 (odd length).

    Dry run

    10 
    21 
    32 
    23 
    14 
    x12321
    half0

    Start with x = 12321. It is not negative and does not end in 0, so keep going. half starts at 0.

    Step 1 of 5

    The plan

    if x < 0 or (x mod 10 == 0 and x != 0):
        return false                 # negatives and numbers ending in 0
    
    half = 0
    while x > half:
        half = half * 10 + x mod 10  # move the last digit of x onto half
        x = x div 10
    return x == half or x == half div 10   # even length, or odd length with the middle digit dropped
    

    Complexity

    Time
    O(d)
    Space
    O(1)

    d is the number of digits. The loop handles only about half of them. Only two variables are used.

    Edge cases

    • Negative numbers such as -121 return false.
    • 0 returns true. The loop does not run, and 0 == 0.
    • 10, 100 and other numbers ending in 0 return false because of the first check.
    • Single digits such as 7 return true: one move gives x = 0 and half = 7, and 0 == 7 / 10.
    • 2147483647 returns false without any overflow, because half stops at about half the digits (746384 here).
    I've built my logic, show the code

    Java

    class Solution {
        public boolean isPalindrome(int x) {
            if (x < 0 || (x % 10 == 0 && x != 0)) {
                return false;
            }
            int half = 0;
            while (x > half) {
                half = half * 10 + x % 10;
                x = x / 10;
            }
            return x == half || x == half / 10;
        }
    }

    C++

    class Solution {
    public:
        bool isPalindrome(int x) {
            if (x < 0 || (x % 10 == 0 && x != 0)) {
                return false;
            }
            int half = 0;
            while (x > half) {
                half = half * 10 + x % 10;
                x = x / 10;
            }
            return x == half || x == half / 10;
        }
    };

    Python

    class Solution:
        def isPalindrome(self, x: int) -> bool:
            if x < 0 or (x % 10 == 0 and x != 0):
                return False
            half = 0
            while x > half:
                half = half * 10 + x % 10
                x = x // 10
            return x == half or x == half // 10

    Common mistakes

    • Skipping the "ends in 0" check. For 10 the loop ends with x = 0 and half = 1, and 0 == 1 / 10 is true, which is wrong.
    • Comparing only x == half, which fails every odd-length palindrome such as 121.
    • Reversing the whole number in a 32-bit variable, which can overflow for large inputs.
    • Forgetting that negatives are never palindromes.

    Similar problems