233. Number of Digit OneTotal accepted:20083Total submissions:79485 difficulty:hard
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.
Idea: Accumulate the total number of each digit is 1 o'clock.
For a specific number of n, the total number of occurrences of 1 is ones. Right-to-left position I (bit 1th digit) NI has
(1) ni==0,ones+=n/10i+1*10i;
(2) ni==1,ones+=n/10i+1*10i+n%10i+1;
(3) ni>1,ones+= (n/10i+1+1) *10i;
Code:
The basic code should look like this:
1 classSolution {2 Public:3 intCountdigitone (intN) {4 intb;5 Long Longones=0;6 for(Long Longm=1; m<=n;m*=Ten){7a=n/m;8b=n%m;9 if(a%Ten==0){Tenones+=a/Ten*m; One Continue; A } - if(a%Ten==1){ -ones+=a/Ten*m+ (b +1); the Continue; - } -ones+= (A/Ten+1)*m; - } + returnones; - } +};
Here's a tip: ones+= (a+8)/10*m+ (a%10==1) * (b+1)
1 /*2 why the type of M is long long: because m may exceed the range of int after the last 1 loops. 3 For example n=1410065408, if the type of M is int, then after m=1000000000, after m*=10, M overflows, M will still satisfy the condition m<=n and continue to loop. But that's not right. So the type of M is a long long. 4 */5 classSolution {6 Public:7 intCountdigitone (intN) {8 intb;9 Long Longones=0;//obviously, the sum of 1 may exceed the range of intTen for(Long Longm=1; m<=n;m*=Ten){ Onea=n/m; Ab=n%m; -ones+= (A +8)/Ten*m+ (a%Ten==1) * (b +1); - } the returnones; - } -};
Leetcode 233. Number of Digit One