Check if a given number is a palindrome or not ?
Palindrome programs are often the first moment where beginners realize that programming is not about syntax, it’s about thinking logically. With just division and modulus, you can solve what looks like a complex problem or If I tell you, What if you could reverse a number without converting it to a string? The palindrome problem in C teaches exactly that—and it’s more elegant than you think. In fact the palindrome number problem appears in exams, interviews, and coding tests, but most explanations skip the logic. Let’s break it down visually and mathematically.
A palindrome number is a number that reads the same when written forward and backward. Examples include:
- 121
- 11
- 2332
Palindrome means both the original string and the reversed string are one and the same or they are equal. Let’s write a program to check if a given number is a palindrome or not and break down the logic / technique behind it. We do with simple mathematical manipulation and without converting the number into a string.
The Funda
The basic funda is you need to extract the last digit. Extracting the last digit can be done by dividing the number by 10 and then getting the remainder.
Add that last digit obtained, to the reversed number.
Create a new number without the last digit, or remove the last digit because the last digit is used to build reversed number.
and repeat the above steps as long as the number is greater than zero.
Step-by-Step Breakdown
Let us understand the logic clearly.
1. Extracting the Last Digit
To extract the last digit of a number, we use the modulus operator (%).
last_digit = number % 10;
So that is the whole thing and once you are done with removing that last digit from that number. You divide the number by 10, if you divide it by 10, and then you get the a new number with the last digit removed.
Example:
123 % 10 = 3
This gives us the rightmost digit of the number.
2. Building the Reversed Number
To construct the reversed number, we:
- Multiply the existing reversed value by
10
(this creates space for a new digit) - Add the extracted digit to it
