Number of Digit One
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to N.
For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers:1, 10, 11, 12, 13.
Hint:Beware of overflow.
If you calculate the number of 1 in each number between 1-n and then add it, you get the result, but the time is over.
Through analysis can be found that the total number of 1 appears equal to A, ten, hundred, Thousand ... Each of these bits has a sum of 1 of the numbers.
Raise a chestnut first to calculate the number of occurrences of the Hundred 1.
Suppose n=123023,a=1230,b=23, then hundred appears 1, the hundred above can be 0-122, at this time hundred below has 0-99, altogether has 123*100 species;
Suppose n=123123,a=1231,b=23, then hundred appears 1, hundred above can be 0-122, at this time hundred below have 0-99, plus hundred above 123, hundred below 0-23, total has 123*100+23+1 species;
Suppose n=123223,a=1232,b=23, then hundred appears 1, the hundred above can be 0-123, at this time hundred below has 0-99, altogether has 124*100 species;
Suppose n=123323, ibid.
You can draw a rule hypothesis to calculate the number of 1 occurrences on the Hundred, M=100,a=n/m,b=n%m:
If a%10==0, there are a/10*m species;
If a%10==1, there are a/10*m+b+1 species;
If a%10>=2, there are (a/10+1) *m species.
For other bits on M different, the law is the same.
1 classSolution {2 Public:3 intCountdigitone (intN) {4 intresult=0;5 for(Longm=1; m<=n;m*=Ten)6 {7 inta=n/m;8 intb=n%m;9 if(a%Ten==0)Ten { Oneresult+= (A/Ten*m); A } - Else if(a%Ten==1) - { theresult+= (A/Ten*m+b+1); - } - Else - { +result+= (A/Ten+1)*m; - } + } A at returnresult; - } -};
[Leetcode] Number of Digit One