First, the experimental topic
Given a positive decimal integer, write down all integers starting at 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~n, for example: f (12) = 5;
2, in the 32-bit integer range, satisfies the condition "F (N) =n" The maximum N is how much;
Second, design ideas
Law:
There are only three cases on each of them: 0,1,2-9
The first digit is the No. 0 digit, and 10 is the 1th place .... ):
0:num/(10^ (i+1)) * (10^i)
1:num/(10^ (i+1)) * (10^i) +num% (10^i) +1;
2-9: (num/(10^ (i+1)) +1) * (10^i)
Third, the core source code
1#include <iostream.h>2#include <math.h>3 4 intSHU1 (intnum)5 { 6 intFlags1;//number of digits in Mark Count 1 (1 bits, 10 10 bits)7 intnow=0;//current number of digits8 intlow=0;//lower number of digits9 intHigh=0;//high number of digitsTen intCount=0; One A while(num/flog!=0) - { -now= (num/flog)%Ten; thelow=num-(num/flog*flog); -high=num/(flog*Ten); - if(num<=0) - return 0; + if(0==now)//the current number is 0 o'clock Count - { +count+=high*flog; A } at Else if(1==now)//the current number is 1 o'clock Count - { -count+=high*flog+low+1; - } - Else - { incount+= (high+1)*flog; - } toflog=flog*Ten;//number One left shift + } - returncount; the } * voidMain () $ {Panax Notoginseng intnum; - intmax=0; thecout<<"Please enter a value to test:"; +Cin>>num; Acout<<"The number of "1" appears:"<<SHU1 (num) <<Endl; the}
Iv. Procedures:
V. Summary of the Experiment
In this experiment, the most important is to find the number of "1" game in the law, find the law, the Code program will be enlightened.
Number of "1" games