Skip to content

20230803 - 循环嵌套

题目: 统计 1~n 中出现 1的次数

  • 示例: n=1 -> 1; n=11 -> 3 (即 1 中有 1个 1, ..., 11 中有 2个 1);

  • 参考答案:

    cpp
    #include <iostream>
    
    using namespace std;
    
    int main() {
        int n=0, count=0;
        cin >> n;
    
        for (int i=1; i <= n; i++) {
            int a = i;
            while (a!=0) {
                if (a % 10 == 1) {  // 取 a(i) 的个位
                    count ++;
                }
    
                a /= 10;  // 将 a 缩小到原来的 1/10, 百位  -> 十位, 十位 -> 个位, 以此缩小
            }
        }
    
        cout << count << endl;
        system("pause");
        return 0;
    }
  • 我的答案:

    cpp
    #include <iostream>
    
    using namespace std;
    
    int main() {
        int n=0, count=0;
        cin >> n;
    
        for (int i=1; i <= n; i++) {
            string c = to_string(i);
            for (int j=0; j < c.length(); j++) {
                if (c[j] == '1') {
                    count ++;
                }
            }
        }
    
        cout << count << endl;
        system("pause");
        return 0;
    }