This problem belongs to the problem that need to find the law. First think of the simplest case: N = 10^n-1
Note X[i] represents 1 of the number from 1 to 10^i-1, then there is the following recursive formula: X[i] = ten * X[i-1] + 10^ (i-1)
This recursive formula can be observed in this way:
i = 0, x[0] = 0
i = 1, from 1 to 9, x[1] = 1
i = 2, from 1 to x[2] = 20: It can be imagined that all the numbers are written in two-digit numbers (such as 1 written 01, 2 as 02), we do not count the highest bit of 1, first at least ten * x[1] 1, then we consider the highest bit of 1, it only exists in 11, 12...19, also 10
i = 3, from 1 to 999,x[3] =? : The same first does not count the highest bit of 1, first of all at least ten * x[2] 1, and then the highest bit, should also add 100 (10^ (3-1))
Gradually thinking, the general formula is out: x[i] = ten * X[i-1] + 10^ (i-1)
Remember that the function we want to solve is f (x)
Now we consider the general N, assuming that it represents a 10 binary with n bits: a[n]a[n-1]...a[1]
The result of F (a[i]a[i-1]...a[1]) expressed in c[i]
The recursive process is still similar, but at this point the upper limit of each bit is limited and cannot be freely evaluated from 0 to 9
A[i] = 0 o'clock, c[i] = c[i-1]
A[i] = 1 o'clock: c[i] = x[i-1] + c[i-1] + a[i-1]a[i-1]...a[1] + 1
A[i] > 1 o'clock: c[i] = a[i] * X[i-1] + Ten ^ (i-1) + c[i-1]
int base = 10;vector<int> digits;while (n >= 1) {digits.push_back (n base); n/= base;} Vector<int> Nums;int s = 0;base = 1;for (int i = 0; i < digits.size (); i++) {s + = base * Digits[i];nums.push_back (s); base *= 10;} Vector<int> C (digits.size () + 1, 0);vector<int> X (digits.size () + 1, 0); base = 1;for (int i = 1; i < c.size (); i++) {X[i] = ten * X[i-1] + base;if (digits[i-1] = = 0) {C[i] = c[i-1];} else if (digits[i-1] = = 1) {C[i] = X[i-1] + c[i-1] + 1 + (i > 1? nums[i-2]: 0);} else {C[i] = digits[i-1] * X[i-1] + c[i-1] + base;} Base *= 10;} Return C[c.size ()-1]; }
Leetcode 233 number of Digit one