The beauty of programming has a problem of the number of occurrences of 1. Given a decimal positive integer N, write down all the positive integers from 1 to n, and then count the number of occurrences of 1; if you change this question a little, you need to count the numbers containing 1. For example, n = 12, F (n) = 4, (1, 10, 11, 12)
It seems that the problem is basically the same, but the two are actually quite different. The changed problem should be said to be a problem of arrangement and combination;
Here is a solution: first, the problem is converted to: calculate the number of numbers without 1, set n = high ow from the highest bit high, set the current total bit + 1 bit 1. obtain 0 ~ High999 .. the number of numbers not included in 1. We can see from the combination problem that there are: high * 9 ^ bit .., 2. the number obtained from 1 is n + 1 ~ High999 the numbers must be subtracted from 2.1. If the value is high = 1, all these numbers contain 1 and are ignored directly. 2.2 otherwise: considering that the maximum values of these numbers are high, if the value is not 1, it can be omitted. Therefore, it is changed to F (999 ..) -F (low); F (999 ..) easy to calculate. The value is 9 ^ bit; Algorithm The complexity is O (BIT), which can be regarded as a constant. Now 0 ~ is obtained ~ Number of numbers not included in 1 between N; 0 ~ If n is a total of N + 1 numbers, then f (n) = n + 1-F (n) is written according to the train of thought. Program As follows: <textarea cols="50" rows="15" name="code" class="cpp"><Br/> int _ countnon1ton (int n) <br/> {<br/> If (n <= 0) return 1; <br/> If (n <10) return N; <br/> int high = 0, low = 0, ibit = 0; <br/> int TMP = n, factor = 1, Count = 1, tmp2 = 1; <br/> // count bit <br/> while (TMP> 9) <br/> {<br/> TMP/= 10; <br/> ibit ++; <br/> factor * = 10; <br/> count * = 9; <br/> tmp2 * = 9; <br/>}< br/> high = N/factor; <br/> low = n % factor; <br/> COUNT = high * count; <br/> If (high = 1) return count; <br/> return count-tmp2 + _ countnon1ton (low ); <br/>}</textarea>