First, title:
Given a positive integer in decimal, write down all integers starting with 1, to N, and then count the number of "1" that appears. Requirements: 1. Write a function f (n) and return the number of "1" that appears between 1 and N. For example F (12) = 5. 2. In the range of 32-bit integers, the maximum n of "f (n) =n" satisfying the condition is what.
second, the idea:This problem is biased toward mathematical reasoning, its fundamental is to find the law, and the law is to be given to the number of decomposition, divided into a Chichong equal number of individuals, and then from each to find the law. Through the collation, each of the number of 1 only with its two-bit relationship, the specific algorithm program is as follows:
third, the source program
1 #include <iostream.h> 2 #include <stdlib.h> 3 int main () 4 {5 int num; 6 int count=0; 7 int flog=1; 8 int low=0; 9 int now=0;10 int high=0;11 cout<< "Please enter Number: "; cin>>num;13 While (num/flog!=0) { low=num-(num/flog) *flog;16 now= (num/flog)%10;17 high= num/(flog*10), switch (now), 0:21 count=count+high*flog;22 break;23 Case 1:24 count=count+high*flog+low+1;25 break;26 default:27 count=count+ (high+1) *flog;28 break;29 } The number of digits 1 in flog=flog*10;31}32 cout<<num<< "is:" <<count<<endl;33 Return 0;34}
Four: Experiment
V. Summary of the Experiment
At first, our idea was to find a general formula, but after thinking about it for a while, it was not a formula to solve, so the best way is to find the law. After summing up with our companions, we discovered the law and finally realized the program.
Pair development----Find a