I. Topics and 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.
- 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, design ideas
The number of 2-digit and 3-digit 1 is calculated first, and then the algorithm of 1 is recursively programmed.
Third, the experimental code
#include <iostream.h>intMain () {intnum; inttag=1; intCount=0; intHeigher,cur,lower; cout<<"Please enter data:"; CIN>>num; while(num/tag!=0) {Heigher=num/(tag*Ten); Cur= (Num/tag)%Ten; Lower=num%tag; Switch(cur) { Case 0: Count=count+heigher*tag; Break; Case 1: Count=count+heigher*tag+lower+1; Break; default: Count=count+ (heigher+1)*tag; Break; } tag=tag*Ten; } cout<<"1 The number of occurrences is:"<<count<<Endl; return 0;}
Four, the experiment:
Looking for 1 in the series