创建后续数字更大的数字:C ++

时间:2013-10-14 08:11:07

标签: c++ logic

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

e.g。

应输出

5678
5679
5689
5789
6789

这是唯一可能的4位数字,后续数字大于之前的数字。

Similarty numbers(3,3)应输出:

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

希望我明白我的问题。尝试了很多,但我无法实现逻辑。

由于

1 个答案:

答案 0 :(得分:2)

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

我修复了代码以符合您的确切要求,并添加了一个简单的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);
}