Question:
Enter an integer n to calculate the number of times 1 appears in the decimal representation of the n integers from 1 to n. The efficiency is as high as possible.
For example:
F (2) = 1
F (12) = 5
F (20) = 12
F (115) = 44
Solution:
The simplest method is to process from 1 to n cyclically, calculate the number of 1 in each number, and accumulate it. This is very inefficient.
The second method is to accumulate the number of digits from 1 to n, such as 10 digits and hundreds of digits. The number of 32-bit integer operations cannot exceed 10 times.
Int numberof1 (int n) {int sum = 0; int factor = 1; int n2 = n; // remainder of n/[1 | 10 | 100 | 1000 |...] // The remainder of n % 1, n % 10, n % 100, n % 1000 int remainder = 0; while (n2> 0) {// variable num is number of 1 in place of units, from 1 to n2 // The variable num indicates the number of 1 in one from 1 to n2 int num = (n2 + 9)/10; // variable true_num is number of 1 in place of units/tens/hundreds/thousands /... (place is determined by factor), from 1 to n // variable true _ Num indicates the number of 1 values (single/ten/hundred/thousands/...) corresponding to the factor (1/10/100/1000/...) from 1 to n. // The complexity is here. For n, if this bit is 1, special processing is required. Int true_num; if (n2% 10 = 1) {true_num = (num-1) * factor + remainder + 1;} else {true_num = num * factor;} sum + = true_num; n2/= 10; factor * = 10; remainder = n % factor;} return sum ;}
You can manually check, or use the secure but inefficient method. I checked it manually and it should be okay.