Counting page numbers 0 ~ 9 The number of times the page appears, and the page number is 0.
The simplest method is to traverse each number in sequence, but this algorithm is too time-complex. If we use recursion, a large number of memory will pop up, and the time-space complexity will be high, which is intolerable.
Therefore, we have found a satisfactory method.
The idea is to calculate the number of number 1 in "the beauty of programming" (Note: if you haven't read it, please preview it first to understand the following code ), expand it (Note that the number 0 cannot appear in the highest bit ). The time complexity is O (logn + 1) and the space complexity is O (1 ).
The language used here is C ++, which has passed the dataset test.
// 0 ~ 9 The number of occurrences. The idea is to calculate the number 1 in the beauty of programming, and to extend the // program format (positive integer in the input: long range; output: 0 ~ 9. the number of times each number appears, separated by spaces) # include <iostream> # include <vector> // # include <bits/stdc ++. h> using namespace std; long counteach (long n, int I) // count the number of I occurrences {long iCount = 0; long iFactor = 1; long iLowerNum = 0; long iCurrNum = 0; long iHigherNum = 0; while (n/iFactor! = 0) {iLowerNum = n-(n/iFactor) * iFactor; iCurrNum = (n/iFactor) % 10; iHigherNum = n/(iFactor * 10 ); if (iCurrNum <I) iCount + = iHigherNum * iFactor; else if (I = iCurrNum) iCount + = iHigherNum * iFactor + iLowerNum + 1; else if (iCurrNum> I) iCount + = (iHigherNum + 1) * iFactor; // process the number of 0 records. // if n is 1 digit, for example, it is originally 1 2 3 4 5 6, previously processed to 0 1 2 3 4 5 6, added 1 0 // if n is 2 digits, for example, it was originally 1 2 3 4 5 6 7 8 9 10 11 12, previously processed as 00 01 02... 09 10 11 12, add 1 + 10 more 0 // If n is 3 digits, for example, it is originally 1 2 3 4... 115, previously processed as 000 001 002... 009 010 011... 099 100... 115, adding 1 + 10 + 100 zeros // Therefore, You need to subtract the number of zeros for multiple computations in each layer loop if (0 = I) iCount-= iFactor; iFactor * = 10;} return iCount;} vector <long> count (long n) // counts 0 ~ 9 {vector <long> res (10, 0); for (int I = 0; I <10; I ++) {res [I] + = counteach (n, i);} return res;} int main () {long n; cin> n; if (n <1) {cout <"n must be a positive integer" <endl; return 0 ;}vector <long> res = count (n); for (int I = 0; I <res. size (); I ++) {I = 0? Cout <res [I]: cout <"" <res [I];} return 0 ;}
Feel the charm of algorithms with your heart.