创建一个子请求数字更大的数字:C++

Creating a number where subsequest digits are greater : C++

本文关键字:数字 C++ 请求 一个 创建      更新时间:2023-10-16

我必须写一个函数说numbers(int MSD,int num)这样,如果我调用该函数作为numbers(5,4),它应该生成所有大于 5000 的 4 位数字,其中后续数字更大。

例如

它应该输出

5678
5679
5689
5789
6789

这是唯一可能的一组 4 位数字,其中后续数字大于前一个数字。

相似性numbers(3,3)应输出:

345
346
347
348
349
356
357
358
359
...
...
456
457
...
789

希望我把我的问题说清楚。尝试了很多,但我无法实现逻辑。

谢谢

你可以使用递归...(或将下面的代码转换为迭代代码)在这个例子中,我打印到标准输出,但你可以用生成的数字做任何你想做的事情。

我修复了代码以匹配您的确切请求,并添加了 PoW 的朴素实现。

int Pow(int a, int b)
{
    int res = a;
    for (int i = 0 ; i < b-1 ; ++i)
    {
        res *= a;
    }
    return res;
}
void numbersInternal(int MSD,int num,int _base)
{       
    if (num == 1)
    {
        for (int j = MSD ; j <= 9 ; ++j)
        {
           cout << _base + j << endl;    
        }
    }
    else
    { 
        for (int j = MSD ; j <= 9-num+1 ; ++j)
        {
            numbersInternal(j + 1,num-1,_base + Pow(10,num-1)*j);        
        }
    }
}
void numbers(int MSD,int num)
{    
    numbersInternal(MSD,num,0);
}