The number of times "1" appears in the number 0-N for classroom exercises.
I. Questions and requirements
Question: Given a decimal positive integer, write down all integers from 1 to N, and then count the number of "1.
Requirements: 1. Write a function f (N) and return the number of "1" between 1 and N. For example, f (12) = 5.
2. In the 32-bit integer range, what is the maximum N of "f (N) = N" that meets the condition.
Ii. Design Ideas
First thought:
Modulo 10, except for 10, and then find the rule,
9% 10 = 9, 9/10 = 0;
11% 10 = 1, 11/10 = 1;
15% 10 = 5, 15/10 = 1;
······
Then I wrote a lot. What should I do if mod 10 is equal to 0? What if it is equal to 1? What should I do when I get the remainder and how do I write the judgment conditions?
I haven't figured it out for a long time.
The second approach (the teacher's thinking in class ):
F (13) = 2 + 4 = 6
F (23) = 3 + 10 = 13
F (33) = 4 + 10 = 14
F (93) = 10 + 10 = 20 ...... The number of first digit is related to the number of first digit, the number of second digit, and the number of second digit. The programming implementation is as follows: 3. Source Code
1 // hanxuedong 2 3 # include <iostream. h> 4 int Count (int n) 5 {6 int count = 0; // Count the number of pairs 1 7 int now = 1; // N from the nth bit to the highest bit. At this time, it corresponds to the first digit of now 8 int l = 0; // The ninth digit of now 9 int nownum = 0; // The number 10 int h = 0 for the now digit; // The number 11 if (n <= 0) 12 {13 return 0 for the first digit of the now digit; 14} 15 while (n/now! = 0) 16 {17 l = n-(n/now) * now; 18 nownum = (n/now) % 10; 19 h = n/(now * 10 ); 20 if (nownum = 0) 21 {22 count + = h * now; 23} 24 else if (nownum = 1) 25 {26 count + = h * now + l + 1; 27} 28 else29 {30 count + = (h + 1) * now; 31} 32 now * = 10; 33} 34 return count; 35} 36 void main () 37 {38 int number; 39 cout <"enter a number:"; 40 cin> number; 41 cout <"0 --" <number <"1 appears for:" <Count (number) <endl; 42}
Iv. Running results
5. Experiences
For this type of questions, finding a rule is very important. Finding a rule will be of great help to code implementation and code optimization. Don't rush to write code, be sure to write down the following rules first.