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