public static int countDigit(int n, int d) {
int cnt = 0;
long i = 1; //位数
while (n / i > 0) {
long leading = n / (i * 10);
long rest = n % i;
long curr = n % (i * 10) / i;
if (d != 0)
cnt += leading * i;
else {
cnt += leading == 0 ? 1 : (leading - 1) * i;
}
// avoid leading 0s
if ((d != 0 || leading > 0) && (d != 0 || i != 1)) {
if (curr > d)
cnt += i;
else if (curr == d)
cnt += rest + 1;
}
i *= 10;
}
return cnt;
}