DEV Community

Cover image for C# LeetCode 9: Palindrome Number - (Easy)
Grant Riordan
Grant Riordan

Posted on

C# LeetCode 9: Palindrome Number - (Easy)

Problem Description:

Given an integer x, return true if x is a palindrome, and false otherwise

Code:

public class Solution
{
    public bool IsPalindrome(int x)
    {
        // we know it can't be a palindrome
        if (x < 0) return false;

        var oNum = x;
        var rNum = 0;

        while (x > 0)
        {
            var digit = x % 10;
            rNum = rNum * 10 + digit;
            x = (int)Math.Floor((decimal)(x / 10));
        }

        return rNum == oNum;
    }
}
Enter fullscreen mode Exit fullscreen mode

Approach

The approach is to reverse the integer and compare it to the original value.

If the reversed number equals the original number, it is a palindrome; otherwise, it is not. This avoids extra memory for strings and checks each digit only once.

Step Through

var digit = x % 10;
rNum = rNum * 10 + digit;
x = (int)Math.Floor((decimal)(x / 10));
Enter fullscreen mode Exit fullscreen mode

% 10 gives the remainder when dividing by 10, which is the last digit of the number.

Example: 123 % 10 = 3

then

rNum = rNum * 10 + digit;
Enter fullscreen mode Exit fullscreen mode
  • Multiply rNum by 10 to shift its digits left.
  • Add the extracted digit to append it to the end.

Example:
rNum = 12;
digit = 3;
rNum * 10 + digit = 123

x = (int)Math.Floor((decimal)(x / 10));
Enter fullscreen mode Exit fullscreen mode

Divide by 10 to drop the last digit.

Floor ensures it truncates toward zero (though integer division in C# already does this).

Example: 123 / 10 = 12

Iteration Current x digit = x % 10 rNum = rNum * 10 + digit New x = x / 10
1 1234 4 0*10 + 4 = 4 123
2 123 3 4*10 + 3 = 43 12
3 12 2 43*10 + 2 = 432 1
4 1 1 432*10 + 1 = 4321 0

And there you have a simple solution, of reversing the number, and then comparing.

Another option is the two‑pointer approach, where you convert the number to a string and use a left and right pointer to compare digits from the outside in. While easier to visualise, it requires extra space for the string conversion.

Drop me a follow to see more articles like this via DevTo or twitter

Top comments (0)