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.
How to solve a problem: when calculating the number of 1 on any one, it is affected by three factors: the number on that bit, the low number, and the high number.
If the number of the bit is 0, the number of bits 1 is determined by the high, and is equal to the high number * The current number of digits.
If the digit of this bit is 1, then the number of bits 1 is determined by the high order and the low position, and is equal to the high number * The current number + the low number + 1.
If the number of the bit is greater than 1, the number of bits 1 is determined by the high, and equal to (the high number + 1) * The current number of digits.
1 Public classSolution {2 Public intCountdigitone (intN) {3 if(n <= 0) {4 return0;5 }6 intnum =N;7 intCurrnum = 0;8 intLowernum = 0;9 intHigernum = 0;Ten intFactor = 1; One intCount = 0; A while(num! = 0) { -Lowernum = N-num *factor; -Higernum = NUM/10; theCurrnum = num% 10; - if(Currnum = = 0) { -Count + = Higernum *factor; -}Else if(Currnum = = 1) { +Count + = Higernum * factor + Lowernum + 1; -}Else { +Count + = (higernum + 1) *factor; A } atFactor = factor * 10; -num = NUM/10; - } - returncount; - } -}
Number of Digit One