题目:
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
Example:
Input: 13
Output: 6
Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
public class NumberDigitOne {
public int countDigitOne(int n) {
int count = 0, previous = 0, coef = 1;
while (n > 0) {
int remain = n % 10;
int over = n / 10;
if (remain > 1) {
count += coef;
} else if (remain == 1) {
count += previous + 1;
}
count += coef * over;
previous += coef * remain;
coef *= 10;
n /= 10;
}
return count;
}
public static void main(String[] args) {
int n = 1410065408;
System.out.println(new NumberDigitOne().countDigitOne(n));
}
}