下一个回文生成器

  • 本文关键字:回文 下一个 c++
  • 更新时间 :
  • 英文 :


我正在尝试找到下一个回文数。我正在尝试调用一个名为 fun() 的函数来检查数字是否回文。我的代码没有按预期工作...任何帮助将不胜感激。

#include<iostream>
using namespace std;
bool fun(int n) {
    int m=n,r,re=0;
    while(n!=0) {
         r=n%10;
         re=re*10+r;
         n=n/10;
    }
    if(re==m) {
        return true;
    }
    else { 
        return false;
    }
}
int main() {
     int t;
     cin>>t;
     while(t--)//no of test cases
     {
         int n;
         cin>>n;
         n=n+1;
         if(fun(n)==true) {
             cout<<n<<"n";// should print a number
             continue;
         }
         else {
             n=n+1;
             fun(n);// call for next number to be Palindrome
         }
     }
}
// if input : 808 output be 818 to be displayed on screen..

循环的逻辑都是错误的。你需要两个循环,外循环用于测试用例,内循环是找到下一个回文。像这样的东西

int main()
{
    int test_cases;
    cin >> test_cases;
    for (int i = 0; i < test_cases; ++i)
    {
        int num;
        cin >> num;
        num = num + 1;
        while (!is_palindrome(num))
        {
            num = num + 1;
        }
        cout << num << "n";
    }
}

我已经重命名了一些变量和函数。像tnfun这样的名称是不够的。选择好的变量名称有助于理解自己的代码,更不用说其他任何人了。

注意内部循环,它循环直到找到回文,这就是为什么它使用 not,!is_palindrome(num) .当找到回文时,内部循环将退出,然后才打印数字。我认为这个逻辑是你的主要错误,你在真正需要while循环的地方使用了if

我还没有检查你的回文测试功能。那里也可能有错误。

最新更新