DEV Community

Shiki Endou
Shiki Endou

Posted on

Solving the 'Palindrome Number' on LeetCode with C++

Problem

https://leetcode.com/problems/palindrome-number/

Answer

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;

        long reversedX = 0;
        int originalX = x;
        while (x != 0) {
            reversedX = reversedX * 10 + x % 10;
            x /= 10;
        }

        return originalX == reversedX;
    }
};
Enter fullscreen mode Exit fullscreen mode

Let's consider a solution to this problem.

We want to know whether an integer is a palindrome or not.

It's simple. If an integer and its reversed form are the same, we know the integer is a palindrome.

Let's analyze the solution as code.

        if (x < 0) return false;
Enter fullscreen mode Exit fullscreen mode

Firstly, if the integer is negative, it's not a palindrome.

        long reversedX = 0;
        int originalX = x;
Enter fullscreen mode Exit fullscreen mode

We define a long variable, reversedX, because it might exceed -2^31 or 2^31.

We define an int variable, originalX, because the value of x will change during the subsequent processes.

        while (x != 0) {
            reversedX = reversedX * 10 + x % 10;
            x /= 10;
        }
Enter fullscreen mode Exit fullscreen mode

We want to reverse x. x % 10 gets the last digit of the integer.
For example, if x is 123, 123 % 10 gives us 3.
Then, we don't need the 3 of 123 and remove it using x /= 10.

This process continues until x is 0.

In the second loop, reversedX already has a value, so we need to add reversedX * 10 to x % 10.
For example, if x is 12 and reversedX is 3, 3 * 10 + 12 % 10 equals 30 + 2 = 32.

If we continue this process until x is 0, we will have reversed the integer.

Lastly, we can determine whether the original integer is a palindrome by comparing reversedX and originalX.

Top comments (0)