Number of Digit One
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.
0 - 10 -> 2
0 - 100 -> 21
0 - 1000 - > 301
0 - 20 -> 11 -> 10 + 1*1
0 - 200 -> 140 -> 100 + 20 * 2
0 - 2000 -> 1600 -> 1000 + 300 * 2
---
d = 0 -> 0
d = 1 -> 1 + remain + len * 10 ^ (len - 1)
1 < d < 9 -> (10 + len * d) * 10 ^ (len - 1)
...
public int countDigitOne(int n) {
if(n <= 0) return 0;
String s = String.valueOf(n);
int count = 0, len = s.length();
for(int i = 0 ; i < len ; i++){
int digit = s.charAt(i) - '0', sub = i != len - 1 ? Integer.parseInt(s.substring(i + 1)) : 0, tmp = digit * (len - i - 1) * (int) Math.pow(10, len - i - 2);
count += digit > 0 ? tmp + (digit > 1 ? (int) Math.pow(10, len - i - 1) : sub * digit + 1) : 0;
}
return count;
}