Leetcode – Palindrome Number

This one was a little more tricky than the last.

Name: Palindrome Number
Difficulty: Easy
Description: Return true if a number reads the same backwards, false otherwise.


Given 121 return true
Given 10 return false
Given -121 return false, because 121- is not the same as -121.

To solve this problem, I first copied the original number (x) to another variable (target). I need to preserve target for the final comparison, but need to mutate x to get the reverse value.

The reverse value (y) is initialized to zero. Looping over x I multiply y by 10. Using modular, I then get the last digit of x and add it to y. Lastly, I remove the last digit from x.

Performance was pretty good, but a bit high on the memory usage:

bool isPalindrome(int x) {
    if (x < 0) return false;

    uint target = x;
    uint y = 0;

    while (x > 0) {
        y = y * 10 + x % 10;
        x /= 10;

    return target == y;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s