用 C++ 打印范围内所有优秀的数字
此问题中,我们给定 3 个值 L、R 和 d。我们的任务是打印所有好的数字,这些数字在不包含 d 的 L 到 R 范围内。
好的数字是每一位都大于其右侧各位数 (所有都比它低) 相加之和小于的数字。例如,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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP