[Leetcode] Number of Digit One

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.