简体   繁体   English

在 C++ 中打印某个数字是否回文

[英]Print whether a certain number is Palindromic or not in C++

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).我的 C++ 开发控制台中有这个代码,它应该检查给定的输入数字是否是回文(反转时,它仍然是相同的数字)。 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当我输入像 707 或 808 这样明显是回文数的数字时,它会打印第二条语句 707 不是回文数,请帮我纠正它

You are destroying the original input x in while loop.您正在破坏 while 循环中的原始输入 x 。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM