PAT A1049 Counting Ones

Question
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(≤2^30).

Output Specification:
For each test case, print the number of 1’s in one line.

Sample Input:

12

Sample Output:

5

分析:
这是一道典型的数学模型问题,要确定所有可能1的个数,如果通过枚举,由于时间的限制,很有可能会发生超时情况。所以说我们要分析1出现的情况。
首先我考虑到1的出现次数与前面取值的多少有关,所以模糊的建立了一个完全二叉树,树的左右子树是下一位取1和不取1的两种情况,但是考虑到下一位如果是0和1,则树的建立条件完全失效。
所以按照 0 、1 、大于1,有三种情况影响该位出现的数字1的次数:

  1. now == 0 : 那么 ans += left * a; //因为now==0说明now位只有在left从0left-1的时候会产生1,所以会产生left次,但是又因为右边会重复从0999…出现a次
  2. now == 1 : ans += left * a + right + 1;//now = 1的时候就要比上一步多加一个当now为1的时候右边出现0~right个数导致的now为1的次数
  3. now >= 2 : ans += (left + 1) * a;//now大于等于2就左边0left的时候会在now位置产生1,所以会产生left次,但是又因为右边会重复从0999…出现a次
    最终代码如下:
#include<cstdio>
using namespace std; 

int main(){
    int num;
    scanf("%d",&num);
    int a = 1,ans = 0;
    int left,now,right;
    while(num/a){
        left = num / (a*10);
        now = num/a %10;
        right = num % a;
        if(now == 0){
            ans += left*a;
        }else if(now==1){
            ans += left*a +right +1;
        }else{
            ans += (left+1)*a; 
        }
        a *=10;
    }
    printf("%d",ans);
    return 0;
}
原文地址:https://www.cnblogs.com/shuibeng/p/13557290.html