统计1到N之间数字1的个数

题目描述

现在有一个正整数a,请计算1到a之间的整数中,有几个数字1。

输入描述

正整数a。1 <= a <= 10000。

输出描述

一个正整数,即'1'的个数。

样例

输入 12

输出 5

提示

例如a为2时,总共两个数:1,2。此时出现了1个幸运数字'1';当a为12时,总共12个数:1,2,3,4,5,6,7,8,9,10,11,12。 此时出现了5个幸运数字 1”。

代码实现 (C++)

#include <iostream>
#include <string>
using namespace std;

int countOnes(int a) {
    int count = 0;
    for (int i = 1; i <= a; i++) {
        string str = to_string(i);
        count += count(str.begin(), str.end(), '1');
    }
    return count;
}

int main() {
    int a;
    cin >> a;

    int result = countOnes(a);
    cout << result << endl;

    return 0;
}

算法思路

  1. 遍历从1到a的每个整数。
  2. 将每个整数转换为字符串。
  3. 使用count()函数统计字符串中'1'出现的次数。
  4. 将每次统计的结果累加到count变量中。
  5. 最后返回count的值。

原文地址: https://www.cveoy.top/t/topic/pQIh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录