求给定数位与数位之和的最小数字
- 最后更新 : 2021年8月10日
给出两个正整数 P和Q,求只包含数字P和Q的最小整数,使该整数的数字之和为 N。
例子。
**输入。**N = 11, P = 4, Q = 7
**输出。**47
解释。 有两个可能的整数可以由4和7组成,它们的总和是11,即47和74。因为我们需要找到最小的可能值,所以47是需要的答案。**输入。**N = 11, P = 9, Q = 7
**输出。**不可能
解释。 不可能用数字7和9创造一个整数,使其总和为11。
有效的方法。让 我们考虑P大于或等于Q,count_P表示P的出现次数,count_Q表示Q在所得整数中的出现次数。因此,问题可以用等式**(P*count_P)+(Q*count_Q)=N的形式表示,为了使所得整数中的位数最少, count_P+count_Q应该尽可能的少。可以看出,由于P** >=Q,满足(P *count_P)+(Q * count_Q)=N的count_P的最大可能值将是最理想的选择。以下是上述方法的步骤。
- 将count_P和count_Q初始化为0。
- 如果N能被P整除,count_P=N/P,N=0。
- 如果 N不能被P整除,从 N中减去Q,并将count_Q增加1。
- 重复步骤2和3,直到N大于0。
- 如果 N !=0,则不可能生成满足所需条件的整数。否则,生成的整数将是_count_Q乘以Q_,然后是_count_P乘以P。_
下面是上述方法的实现。
C++
// C++ Program of the above approach#include <bits/stdc++.h>using namespace std;// Function to print the minimum// integer having only digits P and// Q and the sum of digits as Nvoid printMinInteger(int P,int Q,int N){// If Q is greater that P then// swap the values of P and Qif (Q > P) {swap(P, Q);}// If P and Q are both zero or// if Q is zero and N is not// divisible by P then there// is no possible integer which// satisfies the given conditionsif (Q == 0 && (P == 0 || N % P != 0)) {cout <<"Not Possible";return;}int count_P = 0, count_Q = 0;// Loop to find the maximum value// of count_P that also satisfy// P*count_P + Q*count_Q = Nwhile (N > 0) {if (N % P == 0) {count_P += N / P;N = 0;}else {N = N - Q;count_Q++;}}// If N is 0, their is a valid// integer possible that satisfies// all the requires conditionsif (N == 0) {// Print Answerfor (int i = 0; i < count_Q; i++)cout << Q;for (int i = 0; i < count_P; i++)cout << P;}else {cout <<"Not Possible";}}// Driver Codeint main(){int N = 32;int P = 7;int Q = 4;// Function CallprintMinInteger(P, Q, N);return 0;} |
输出
47777
时间复杂度。 O(N)
空间复杂度。 O(1)
读者请注意!现在不要停止学习。以学生可接受的价格获得所有重要的DSA概念。 DSA自学课程以适合学生的价格掌握所有重要的DSA概念,并为行业做好准备。 要完成从学习语言到DS Algo以及更多的准备工作,请参考 完整的面试准备课程.
如果你想参加专家的现场课程 ,请参考 面向在职人士的DSA现场课程 和 面向学生的竞争性编程直播课程.
我的个人笔记 arrow_drop_up
保存