[Leedcode 233] Number of Digit One

Source: Internet
Author: User

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.

 Public classSolution { Public intCountdigitone (intN) {/*Intuitive: Every 10 numbers, there is a bit is 1, every 100 number, there are 10 10 bits is 1, every 1000 number, there are 100 hundred is 1.          Make a loop that calculates the total number of 1 on a single bit (digit, 10 bit, hundred). Example: To count hundreds of 1 as an example: Suppose hundreds are 0, 1, and >=2 three cases: Case 1:n=3141092, A= 31410, b=92.            The count of 1 on the Hundred should be 3141 * 100 times. Case 2:n=3141192, A= 31411, b=92.             The count of 1 on the hundred should be 3141 *100 + (92+1). Case 3:n=3141592, A= 31415, b=92.         Calculate the number of 1 on the Hundred should be (3141+1) * 100 times. The above three cases can be summed up in one formula: (A + 8)/ten * M + (a% = = 1) * (b + 1);*/                        //because when n is the highest bit of int (10), when M<=n, this time the m*10 will exceed the 32int range, so I need to declare m as long        intRes=0;  for(LongM=1;m<=n;m=m*10){            inta=n/(int) m; intb=n% (int) m; Res+ = (a+8)/10*m; if(a%10==1) res+=b+1; }        returnRes; }}

[Leedcode 233] 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.