Sword refers to Offer 43. The number of occurrences of 1 in an integer of 1~n

Enter an integer n and find the number of occurrences of 1 in the decimal representation of n integers from 1 to n.

For example, if you enter 12, the numbers containing 1 in the integers from 1 to 12 are 1, 10, 11, and 12, and 1 appears 5 times in total.

Example 1:

Input: n = 12
Output: 5

Example 2:

Input: n = 13
Output: 6

limit:

1 <= n < 2^31

Because it is the number of occurrences of 1, it can be disassembled into 0~n, and how many 1s appear in each digit,
so continue dismantling. For example, 109.
For the ones digit: the
previous cycle is similar to 0~407, and 0~9 appears every time. 1 this 1, so a total of 407*1+ 0 ~ 9, which is 408

For the tens place:
40 times in the previous cycle, each time is 0~100, then for the tens place, there are 10 times,
40*10 + 0 = 400

For the hundreds place: 1 is a bit special, because it is 1 so the low digits should also be counted. For example, 14, then it is 0 10 + 4+1
5
100 + 09 +1=510

So the rule is drawn:
suppose the current position is a, the low position is b, the high position is c

a=0   当前位贡献: c*位数(个位就是1,十位10,百位100)

a=1   当前位贡献:c*位数+b+1

a>1   当前位贡献:c*位数+位数
class Solution {
    
    
public:
    int countDigitOne(int n) {
    
    
        long sum=0;
        int b=0;
        for(long i=1;n!=0;i*=10)
        {
    
    
            int a=n%10;
            int c=n/10;
            if(a==0)
            {
    
    
                sum+=c*i;
            }
            else if(a==1)
            {
    
    
                sum+=c*i+b+1;
            }
            else
            {
    
    
                sum+=c*i+i;
            }
            b=b+a*i;
            n/=10;
        }
        return sum;

    }
};

Guess you like

Origin blog.csdn.net/qq_43624038/article/details/113601803