I have this code in my my C++ dev console that is supposed to check if a given input number is palindromic(when reversed, its still the same number). The problem is that i don't know how to iterate through the calculations to check whether its true and print the required statements
#include <iostream>
using namespace std;
bool isPalindrome(int x) {
int rev=0;
//complete the function
while(x>0){
rev = rev*10 + x%10;
x = x/10;
cout<<rev<<endl;cout<<x<<endl;
}
if(x==rev){
return true;
}else{
return false;
}
}
int main() {
int n;
cin >>n;
if(isPalindrome(n)) {
cout <<n<<" is a palindrome";
}
else {
cout << n<<" is NOT a palindrome";
}
return 0;
}
When i input a number like 707 or 808 which are obviously palindromic, it prints the second statement that 707 is not a Palindrome number, Please help me rectify it
You are destroying the original input x in while loop. Simply copy it in a temporary variable, and it should fix your code. like
bool isPalindrome(int x) {
int rev=0;
int tmp = x;
while(tmp>0){
rev = rev*10 + tmp%10;
tmp = tmp/10;
}
return (x== rev);
}
Why don't you try using this:
#include<iostream>
#include<string>
using namespace std;
bool isPalindrome(string);
int main(){
int n;
cout<<"Enter a number: "<<endl;
cin>>n;
string ntoString=to_string(n);//here I converted the number to string
if(isPalindrome(ntoString))
cout<<n<<" is palindrome"<<endl;
else cout<<n<<" is not palindrome"<<endl;
system("pause");
return 0;
}
bool isPalindrome(string firstString){
for(int i=0;i<firstString.length();i++){
if(firstString[i]!=firstString[firstString.length()-1-i])
return false;
}
return true;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.