• 1049. Counting Ones/整数中1出现的次数(从1到n整数中1出现的次数)


    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~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数。
     
     1 #include<iostream>
     2 #include<string>
     3 #include<sstream>
     4 #include<math.h>
     5 using namespace std;
     6 int CountOne(std::string num)
     7 {
     8     int len = num.length();
     9     if(len == 0)
    10         return 0;
    11     int fir = num[0] - '0';
    12 
    13     if(len == 1 && fir == 0)
    14         return 0;
    15     if (len == 1 && fir >= 1)
    16         return 1;
    17 
    18     int num1 = 0,num2,num3;
    19     if (fir == 1)
    20     {
    21         string re = num ,tem;
    22         num.erase(num.begin());
    23         tem = num;
    24         num = re;
    25         re = tem;
    26         stringstream ss;
    27         ss << re;
    28         ss >> num1;
    29         ++ num1;
    30     }
    31     else if(fir > 1)
    32     {
    33         num1 = pow((double)10,len - 1);
    34     }
    35     num2 = (len -1) * fir * pow((double)10,len-2);
    36     string tnum = num;
    37     tnum.erase(tnum.begin());
    38     num3 = CountOne(tnum);
    39     return num1 + num2 + num3;
    40 }
    41 int main()
    42 {
    43     string num;
    44     cin >> num;
    45     printf("%d
    ",CountOne(num));
    46     return 0;
    47 }
  • 相关阅读:
    centos7安装mysql8 ERROR! The server quit without updating PID file
    linux桌面系统开启windows远程访问
    intellij ide 激活(转发)
    intellij ide调用一个对象所有的set方法
    linux服务器磁盘挂载
    互联网公司研发团队服务器开发工具清单
    intellij ide 集成cmder
    maven 私服上有jar包但是却下载不下来
    java开发人员win10配置
    996 icu我能为你做什么?
  • 原文地址:https://www.cnblogs.com/xiaoyesoso/p/5158761.html
Copyright © 2020-2023  润新知