The following idea was taken from a book named "Sword Point offer" published in China.
Supposen = 271, it then breaks[1, 271]Into[1, 71]and[72, 271]. For[72, 271], the number of1On the hundreds is10^2 = 100(Note that if the digit on the higest bit is1, then the number of1' s on that bit would be72, which is271 % 100 + 1). To compute the number of1On tens and units, we further break[72, 271]Into[72, 171]and[172, 271]. Each interval have10^1 = 101' s on both the Tens and units. So the overall number of1' s on tens and units are2 * 2 * 10^1 = 40. Now we is only left with[1, 71], which can be solved recursively. Theint nis transformed into astring numTo facilitate some operations.
The code is as follows.
1 classSolution {2 Public:3 intCountdigitone (intN) {4 if(N <=0)return 0;5 stringnum =to_string (n);6 returncountone (num);7 }8 Private:9 intCountone (stringnum) {Ten if(Num.empty ())return 0; One intFirst = num[0] -'0'; A if(num.length () = =1) { - if(first)return 1; - return 0; the } - intHighestbit; - if(First >1) Highestbit = Powerten (Num.length ()-1); - Else if(First = =1) Highestbit = Stoi (Num.substr (1)) +1; + intOtherbits = First * (Num.length ()-1) * Powerten (Num.length ()-2); - intRecurcount = Countone (Num.substr (1)); + returnHighestbit + otherbits +Recurcount; A } at intPowerten (intexp) { - intp =1; - for(inti =0; I < exp; i++) -P *=Ten; - returnp; - } in};
This link has a brilliant 4-line solution! The code is rewritten as follows.
1 classSolution {2 Public:3 intCountdigitone (intN) {4 intCounts =0;5 for(intm =1000000000; M M/=Ten)6Counts + = (n/m +8) /Ten* m + (n/m%Ten==1) * (n% m +1);7 returncounts;8 }9};
[Leetcode] Number of Digit One