题目:
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));
}
}
计数数字中1的出现次数
本文介绍了一个算法问题,即计算从0到n的所有非负整数中数字1出现的总次数。通过一个Java实现的例子,展示了如何高效地解决这个问题。示例中包括了对13作为输入的解释,以及一个对大规模数字1410065408进行计算的演示。
2509

被折叠的 条评论
为什么被折叠?



