WAP to check the given number is PALINDROME or NOT
Objective
Write a C++ program to check if a given number is a Palindrome.
Algorithm / Approach
- Read a number
nand store a backup copy inorig. - Initialize
rev = 0. - In a
while(n > 0)loop, extract the last digit:temp = n % 10. - Append it to the reverse variable:
rev = (10 * rev) + temp. - Chop off the last digit:
n = n / 10. - Compare the built
revnumber against theorigbackup.
main.cpp
#include<iostream>
using namespace std;
int main() {
int n,orig,rev = 0;
cout<<"Enter Value for N: ";
cin>>n;
orig = n;
while(n>0) {
int temp = n%10;
rev = 10*rev+temp;
n = n/10;
}
if(orig==rev) {
cout<< orig<<" is Palindrome\n";
}
else {
cout<< orig<<" is not Palindrome\n";
}
return 0;
}
Expected Output
Enter Value for N: 12345 12345 is not Palindrome
Explanation of the Program
- A Palindrome number reads the same forwards and backwards (e.g., 12321).
- By using the modulo operator (
% 10), we extract the right-most digit. By multiplying our running total by 10 before adding the new digit, we mathematically shift all previously extracted digits to the left, perfectly constructing the number in reverse.
Complexity
Time Complexity
O(log₁₀ n)
Space Complexity
O(1)