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 int countDigitOne(int n) {
int res = 0, a = 1, b = 1;
while (n > 0) {
res += (n + 8) / 10 * a;
if(n%10 == 1) res +=b;
b += n % 10 * a;
a *= 10;
n /= 10;
}
return res;
}

本文介绍了一种高效算法,用于计算从1到任意整数n中数字1出现的总次数。通过巧妙地利用数学规律,该算法能够在不遍历每一个数字的情况下得出正确答案。
2511

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



