• 1049 Counting Ones 甲级 xp_xht123


    The task is simple: given any positive integer N, you are supposed to count the total number of 1's in the decimal form of the integers from 1 to N. For example, given N being 12, there are five 1's in 1, 10, 11, and 12.

    Input Specification:

    Each input file contains one test case which gives the positive N (≤230).

    Output Specification:

    For each test case, print the number of 1's in one line.

    Sample Input:

    12
    

    Sample Output:

    5

    解题思路:

    首先,可以想到的一定是暴力的手段,对于每一个数截取出每一位的数字,统计1的个数,如果这样写的话4 和 6测试点会过不了,因为n的范围最大可以到max_int,因此这样的作法并不是最终解法。

     因此,需要寻找结果和给定的n之间的关系

    如果一个数是abcdefg

    if d == 0 
    abc可以的取值是000~(abc - 1)
    efg可以的取值000~999
    总共方案数 abc * 10^3

    if d == 1
        if abc在000~(abc - 1)
        总方案数abc * 10^3
        if abc取abc
        总方案数efg + 1
        综上 abc * 10^3 + efg + 1
        
    if d > 1
    方案数(abc + 1) * 10^3

    综上所述

    错误代码

    1. #include
    2. #include
    3. using namespace std;
    4. int n;
    5. int main()
    6. {
    7. cin >> n;
    8. int res = 0;
    9. for(int i = 1;i <= n;i ++)
    10. {
    11. int j = i;
    12. while(j)
    13. {
    14. if(j % 10 == 1) res ++;
    15. j /= 10;
    16. }
    17. }
    18. cout << res;
    19. }

     正确代码

    1. #include
    2. #include
    3. using namespace std;
    4. int n;
    5. int cal()
    6. {
    7. vector<int>v;
    8. while(n) v.push_back(n % 10) , n /= 10;
    9. int res = 0;
    10. for(int i = v.size() - 1;i >= 0;i --)
    11. {
    12. int x = v[i];
    13. int right = 0 , left = 0 , pow = 1;
    14. //计算左边 (efg)
    15. for(int j = v.size() - 1;j > i;j --) left = left * 10 + v[j];
    16. //计算右边 (abc)
    17. for(int j = i - 1;j >= 0;j --)
    18. {
    19. right = right * 10 + v[j];
    20. pow *= 10;
    21. }
    22. if(x == 0) res += left * pow;
    23. else if(x == 1) res += left * pow + right + 1;
    24. else res += (left + 1) * pow;
    25. }
    26. return res;
    27. }
    28. int main()
    29. {
    30. cin >> n;
    31. cout << cal() << endl;
    32. return 0;
    33. }

  • 相关阅读:
    Vue开发实例(七)Axios的安装与使用
    Sora AI揭秘:短视频创作的智能化之路
    flutter 视频解码器fijkplayer使用
    zabbix部署及监控
    C++标准模板(STL)- 类型支持 (std::size_t,std::ptrdiff_t,std::nullptr_t)
    简单的考试系统
    深度解析KubeEdge EdgeMesh 高可用架构
    开源项目研读AXIOM camera
    Elasticsearch 7和Elastic Stack:深入实践
    机器学习【线性回归算法1】
  • 原文地址:https://blog.csdn.net/xp_xht123/article/details/126531274