First, the topic requirements:
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 solution of ideasBy enumerating several numbers, we can find that the law of function f (n) is as follows: 1. A decimal number: When N>=1, f (n) = 1; When n=0, f (n) = 0; 2. Two-bit decimal number: f (13) = number of single-digit occurrences of 1 + 10-bit occurrence 1 =2+4=6; F (23) = digit 1 number + 10 digit appears 1 number =3+10=13; ... f (93) = number of digits appearing 1 + 10 digits appear 1 number =10+10=20; 3. Three-bit decimal number: f (103) = number of occurrences of 1 digit + 10 digit appears 1 number + hundred appears 1 number = (10+10) +1+100; F (203) =...= (10+10) *2+1+100;
F (303) =...= (10+10) *3+ (1) +100;
......
4.F (ABCDE), calculate the number of C-bit 1, you need to see the case of AB, C, de: When c=0, by the high impact, the number of hundreds of 1 is: (AB) *100 when c=1, by the high and low impact, the number of 1 appears on the Hundred: (AB) *100+ (CDE) +1 When c>1, affected by high, the number of hundreds of 1 appear: ((AB) +1) *100 Three, source code
1#include"iostream.h"2#include"stdlib.h"3 intCountnum (intN)4 {5 intCount=0; 6 intFactor=1; 7 intlowernum=0;8 intcurnum=0;9 inthighernum=0;Ten while(n/factor!=0) One { Alowernum=n-(n/factor) *factor; -curnum= (n/factor)%Ten; -highernum=n/(factor*Ten); the Switch(Curnum) - { - Case 0: -count=count+highernum*factor; + Break; - Case 1: +Count=count+highernum*factor + Lowernum +1; A Break; at default: -count=count+ (highernum+1)*factor; - Break; - } -factor=factor*Ten; - } in returncount; - } to + intMain () - { the intnum; *cout<<"Please enter a number: \ n"; $Cin>>num;Panax Notoginsengcout<<"\ n"; -cout<<num<<"Number 1 appears in the number: \ n"; theCout<<countnum (num) <<Endl; + return 0; A}
Four, the code
Five, experimental experience
When we get to the problem of seemingly no thinking, we can enumerate the representative number, from which to find the law, for example, this experiment, seemingly impossible, but when we put the data of each stage, we can find the law.
Find out the number of "one" that appears in the decimal number