我必须用 C 语言编写一个程序,它接受整数、sumOfDig 和 lengthOfNum。 sumOfDig 等于数字之和,lengthOfNum 等于数字的长度。 我不允许使用数组或 math.lib
1 ≤ sumOfDig ≤ 81 且 1 ≤ lengthOfNum ≤ 9
我尝试编写一个 while 循环,但我想不出一种可以构建数字并从数字总和中减去最后添加的数字的方法。
#include <stdio.h>
#include <stdlib.h>
int main() {
int lengthOfNum; /* stores the length of the number */
int sumOfDig; /* stores the sum of the digits */
int ans; /* stores the answer */
scanf("%d", &sumOfDig); /* scans the sum of the digits */
scanf("%d", &lengthOfNum); /* scans the length of the number */
ans=0; /* initializes ans */
/* adds a number to ans, and removes it from sumOfDig */
while(sumOfDig!=0 && lengthOfNum!=0) {
/*???*/
lengthOfNum--;
};
printf("%d\n", ans); /* prints the outcome */
return 0;
}
以下应该是输入和结果:
输入:20 2 输出:不可能
输入:20 3 输出:992(因为长度为 3 并且 9+9+2=20)
输入:50 8 输出:99999500(因为长度为 8 且 9+9+9+9+9+5+0+0=50)
最佳答案
我们将数字之和称为 S 和指定长度 L。
首先,我们需要检查是否有解决方案。我们需要的最少位数取决于 9 能除 S 的次数。
- 求出 9 是如何整除 S 的。我们称之为 Q。
- 求上述除法的余数。我们称之为 R。
- 如果 R 为 0,
- 如果 L 小于 Q,
- 没有解决方案。
- 如果 L 小于 Q,
- 否则,
- 如果 L 小于 Q+1,
- 没有解决方案。
- 如果 L 小于 Q+1,
现在,我们可以产生输出了。
- 输出Q
9
- 如果 R 不为 0,
- 输出 R。
- 输出 L-Q-1
0
.
- 其他
- 输出 L-Q
0
.
- 输出 L-Q
或
- 输出Q
9
- 将 Z 设置为 L-Q。
- 如果 R 不为 0,
- 输出 R。
- 减少 Z。
- 输出 Z
0
.
还有其他方法。您可以通过在缓冲区中构建输出来避免首先检查输入,甚至在 int
中构建输出。 — 但我使用了一种易于可视化并遵循计算前验证的常用约定的方法。
除法可以作为循环完成,这为您提供了我提到的替代方法的基础。
unsigned R = S;
unsigned Q = 0;
while (R > 9) {
R -= 9;
++Q;
}
关于c - 输出指定长度和和的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58094737/