【发布时间】:2014-11-08 06:27:34
【问题描述】:
我决定编写一小段代码来获取两个整数,假设 M 和 N ( M
#include <iostream>
#include <vector>
using namespace std;
// the partial digits sums digitSum[i] = the sum of the digits between 0 and i
int digitSum[] = {0, 1, 3, 6, 10, 15, 21, 28, 36, 45};
int pow_of_ten[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};
// the sums of all the digits in the numbers from 1 to (10^(i) - 1) where i is the index in the array
long subsums[] = {0, 45, 20 * 45, 300 * 45, 4000 * 45, 50000 * 45, 600000 * 45, 7000000 * 45, 80000000 * 45,
900000000 * 45};
//Calculates the sum of all digits between 0 and M inclusive
long Digit_Sum(int M) {
if (M < 10) {
return digitSum[M];
}
long result = 0;
int same = M;
int counter = 0;
int lastdigit = 0;
while (same > 0) {
if (same < 10) {
lastdigit = same;
break;
}
same /= 10;
counter ++;
}
for(;counter >= 0; counter --) {
result += (subsums[counter] + M % pow_of_ten[counter] + 1) * lastdigit;
result += digitSum[lastdigit - 1] * pow_of_ten[counter];
if (counter == 0) {
break;
}
lastdigit = (M / pow_of_ten[counter - 1]) % 10;
}
return result;
}
int main() {
int M;
int N;
vector<long> sums;
while (true) {
cin >> M >> N;
if (M == 0 && N == 0) {
break;
}
sums.push_back(Digit_Sum(N) - Digit_Sum(M - 1));
}
for (vector<long>::iterator it = sums.begin(); it != sums.end(); ++it) {
cout << *it << endl;
}
}
在大多数情况下,这很有效,但在线法官说这是错误的。我查看了其他可行的解决方案,但没有人像我那样对数组中的值进行硬编码。这可能会导致部分问题,有什么想法吗?
【问题讨论】:
-
你可以用一行循环来执行这个逻辑,为什么所有增加的复杂性?
-
你可以用一个一个简单的表达式来执行这个逻辑,只需计算它。提示:如果您考虑计算两次总和,则可以将其视为一个值序列加上反向序列的总和。
-
简单公式
M*(M+1)/2是不是不能用? -
@RSahu Sahu 如何使用此表格计算序列的位数。
-
我的意思是,到目前为止,显然您已经对两位回答者中的任何一个问题进行了更多思考,并找到了他们甚至没有想过要寻找的模式。但是您需要与我们分享这种想法,以便我们进行故障排除。期望我们从代码中对设计进行逆向工程是疯狂的,而从头开始设计解决方案也是一项过多的工作。
标签: c++ vector iterator sum digits