First, the topic
Given a positive integer in decimal, write down all integers starting with 1, to N, and then count the number of "1" that appears. Requirement: Write a function f (n) to return the number of "1" occurrences between 1 and N. For example F (12) = 5. Within a 32-bit integer range, the maximum n of the "F (n) =n" that satisfies the condition is what. Second, the concept of design can be realized at the beginning of the idea is to traverse each number to 10 to see if it equals to the statistics, but the time complexity is high, not the optimal algorithm. Another better algorithm is to analyze the number of 1 occurrences of a positive integer n, that is, its single-digit, 10-bit, hundred ... The number of the 1. First, look for the law: F (=2+4=6f) =3+10=13f (93) =4+10=14f =10+10=20 ... But the formula is not calculated and cannot be achieved. The algorithm of ergodic type is given. Third, the Code
1#include <iostream.h>2 3 intMain ()4 {5 intCount=0, i,n,temp;6cout<<"Please enter the number n,n=";7Cin>>N;8 for(i=1; i<=n;i++)9 {Tentemp=i; One while(temp!=0) A { -count+= (temp%Ten==1)?1:0; -Temp/=Ten; the } - } -cout<<"F ("<<N<<")="<<count<<Endl; - return 0; +}
Iv. Results of operation
V. Summary
The problem is still the optimal code, but the better algorithm will not be implemented, in the search for the optimal algorithm needs to be improved.
Find out the number of 1 in 1-n