[英]Print whether a certain number is Palindromic or not in C++
我的 C++ 開發控制台中有這個代碼,它應該檢查給定的輸入數字是否是回文(反轉時,它仍然是相同的數字)。 問題是我不知道如何遍歷計算以檢查其是否為真並打印所需的語句
#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;
}
當我輸入像 707 或 808 這樣明顯是回文數的數字時,它會打印第二條語句 707 不是回文數,請幫我糾正它
您正在破壞 while 循環中的原始輸入 x 。 只需將它復制到一個臨時變量中,它就會修復您的代碼。 喜歡
bool isPalindrome(int x) {
int rev=0;
int tmp = x;
while(tmp>0){
rev = rev*10 + tmp%10;
tmp = tmp/10;
}
return (x== rev);
}
你為什么不嘗試使用這個:
#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.