用 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