C# Program to Check Palindrome Number
int reversed = 0; int temp = num; while (temp > 0) { reversed = reversed * 10 + temp % 10; temp /= 10; } bool isPalindrome = (num == reversed);.Examples
How to Think About It
Algorithm
Code
using System; class Program { static void Main() { int num = 121; int reversed = 0, temp = num; while (temp > 0) { reversed = reversed * 10 + temp % 10; temp /= 10; } if (num == reversed) Console.WriteLine($"{num} is a palindrome number."); else Console.WriteLine($"{num} is not a palindrome number."); } }
Dry Run
Let's trace the number 121 through the code to see how it checks for palindrome.
Initialize variables
num = 121, reversed = 0, temp = 121
First loop iteration
reversed = 0 * 10 + 121 % 10 = 1, temp = 121 / 10 = 12
Second loop iteration
reversed = 1 * 10 + 12 % 10 = 12, temp = 12 / 10 = 1
Third loop iteration
reversed = 12 * 10 + 1 % 10 = 121, temp = 1 / 10 = 0
Compare original and reversed
num = 121, reversed = 121, they are equal, so palindrome
| temp | reversed |
|---|---|
| 121 | 0 |
| 12 | 1 |
| 1 | 12 |
| 0 | 121 |
Why This Works
Step 1: Reverse the number
We build the reversed number by taking the last digit of the original number and adding it to the reversed number shifted by one digit using reversed = reversed * 10 + temp % 10.
Step 2: Remove last digit
We reduce the original number by removing its last digit using temp /= 10 to process the next digit.
Step 3: Compare original and reversed
If the reversed number equals the original number, it means the number reads the same forwards and backwards, so it is a palindrome.
Alternative Approaches
using System; class Program { static void Main() { int num = 121; string str = num.ToString(); char[] arr = str.ToCharArray(); Array.Reverse(arr); string revStr = new string(arr); if (str == revStr) Console.WriteLine($"{num} is a palindrome number."); else Console.WriteLine($"{num} is not a palindrome number."); } }
using System; class Program { static bool IsPalindrome(int num, int rev = 0) { if (num == 0) return true; rev = rev * 10 + num % 10; return IsPalindrome(num / 10, rev) && (num == 0 || num == rev); } static void Main() { int num = 121; Console.WriteLine(IsPalindrome(num) ? $"{num} is a palindrome number." : $"{num} is not a palindrome number."); } }
Complexity: O(d) time, O(1) space
Time Complexity
The time depends on the number of digits d in the number because the loop runs once per digit to reverse it.
Space Complexity
Only a few integer variables are used, so space is constant O(1).
Which Approach is Fastest?
The integer reversal method is faster and uses less memory than string conversion, while recursion is less efficient and more complex.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Integer reversal | O(d) | O(1) | Performance and memory efficiency |
| String reversal | O(d) | O(d) | Simplicity and readability |
| Recursive check | O(d) | O(d) | Learning recursion, less practical |