在C ++中打印给定范围内的所有良好数字

在这个问题上,我们给了三个值L,R和d。我们的任务是打印所有好号码 的范围从左至右中不包含d作为其数字。

好的数字是一个数字,其中每个数字都大于其右边的数字之和(所有比其次有效的位)。例如,732是一个很好的数字,即7> 3 + 2和3> 2。

现在,让我们举一个例子来了解这个问题,

Input: L = 400 , R = 500 , k = 3
Output: 410, 420, 421

说明-400到500之间的良好数字是-

410, 420, 421, 430, but we cannot use 3 so 430 is not printed.

为了解决这个问题,为此,我们将检查给定范围(即L到R)中的所有数字,如果一个数字是一个好的数字并且它的任何数字都不等于k,则将其打印,否则保留该数字。

检查好数字-如果总和大于下一个数字,我们将在任何时候从右向左遍历该数字,并保持一个总和,否则返回false。

示例

我们来看一下说明以下算法的程序-

#include<bits/stdc++.h>
using namespace std;
bool isvalidNumber(int n, int d){
   int digit = n%10;
   int sum = digit;
   if (digit == d)
      return false;
   n /= 10;
   while (n){
      digit = n%10;
      if (digit == d || digit <= sum)
         return false;
      else{
         sum += digit;
         n /= 10;
      }
   }
   return 1;
}
void printGoodNumbersLtoR(int L, int R, int d){
   for (int i=L; i<=R; i++){
      if (isvalidNumber(i, d))
         cout << i << " ";
   }
}
int main(){
   int L = 400, R = 600, d = 3;
   cout<<"All good numbers from "<<L<<" to "<<R<<" that do not contain "<<d<<" are :\n";
   printGoodNumbersLtoR(L, R, d);
   return 0;
}

输出结果

All good numbers from 400 to 600 that do not contain 3 are −
410 420 421 510 520 521 540