1 条题解

  • 2

    不走寻常路来一个stl的题解

    题目分析

    我们可以把问题转化成统计字符串里的给定字符的个数

    但是怎么把int转换为string呢? 我们可以使用函数to_string

    int a = 114514;
    string b = a.to_string(i);
    

    同样的,统计个数也不必我们亲自来做

    可以使用count(记得引用头文件algorithm)

    string t = to_string(i);
    ans += count(t.begin(),t.end(),'2');
    

    解决了这些,我们只需要枚举给定的区间,再把每次枚举到的进行以上操作就可以求出答案

    完整代码

    #include <iostream>
    #include <algorithm>
    using namespace std;
    int n, m, ans;
    int main()
    {
        cin >> n >> m;
        for (int i = n; i <= m; i++)
        {
            string t = to_string(i);
            ans += count(t.begin(), t.end(), '2');
        }
        cout << ans;
    
        return 0;
    }
    
    

    stl大法好!

    • 1

    信息

    ID
    53
    时间
    1000ms
    内存
    64MiB
    难度
    3
    标签
    递交数
    108
    已通过
    32
    上传者