用c++写在英美习惯在数字中加进一个千位分隔符,即数字中的逗号,以方便进行计数和认数,比如1234567890,记为1,234,567,890。 小明现在用这个方法从1写到了N,请问他写了多少个逗号。
时间: 2024-02-11 14:08:12 浏览: 117
好的,下面是用C++实现的代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int countCommas(int n) {
int cnt = 0;
for (int i = 1; i <= n; i++) {
int digits = 0, x = i;
while (x > 0) {
digits++;
x /= 10;
}
if (digits <= 3) {
// no commas
} else if (digits <= 6) {
cnt++; // one comma at position 4
} else if (digits <= 9) {
cnt += 2; // two commas at positions 4 and 7
}
}
return cnt;
}
int main() {
int n;
cin >> n;
int ans = countCommas(n);
cout << ans << endl;
return 0;
}
```
代码思路和前面的解决方案基本一致。countCommas函数用于统计从1到n中所有数字中出现的逗号数量总和。在该函数中,我们从1到n枚举每个数字,对于每个数字,我们计算它的位数,然后根据位数判断它在数字中出现的逗号数量。最后将所有数字中出现的逗号数量累加起来,即为答案。在main函数中,我们读入n,然后调用countCommas函数计算答案并输出。
希望我的回答能够帮到你,如果还有任何问题,欢迎随时提出。
阅读全文
相关推荐

















