Check if number is a palindrome
To check if given number is same even if reversed (Palindrome).
Learning Objectives
- Concept of palindrome.
- Reversal of a number.
- Extraction of individual digits of a number.
- Shifing number to it higher place by multiplying it with 10.
Program Approach
- Save the given number in a copied variable.
- Reverse the copied number and save to a different variable.
- Compare original number to reversed number.
Source Code
|
|
Alternate (?) : Related ( ? ) : |
Run Output
Code Understanding
while(nc>0){rem=nc%10;nr=nr*10+rem;nc=nc/10;}
This loop reverses the number kept in nc, the copy of original number in a variable named nr. First nc%10 extracts the last digit then this digit is shifted left by mutiplying it to 10 and then adding the next number, then last number is dropped by using nc/10.
if(n==nr) cout<<“Palindrome”; else cout<<“Not Palindrome”;
If original number n is same is nr the reversed number then we display it as palindrome, else we display not a palindrome.
Notes
This approach will not work on negative integers. One can find absolute number of input to remove the negative sign and then follow this approach.
Suggested Filename(s): palindrome-num.cpp, palin.cpp
Created: 2-Dec-2017 18:00 | Updated: 24-Feb-2018 14:45|
