一、题目:
给定一个十进制的正整数,写下从1开始,到N的所有整数,然后数一下其中出现“1”的个数。要求: 1.写一个函数 f(N) ,返回1 到 N 之间出现的“1”的个数。例如 f(12) = 5。2.在32位整数范围内,满足条件的“f(N) =N”的最大的N是多少。
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<<"请输入数字: ";
12 cin>>num;
13 while (num/flog!=0)
14 {
15 low=num-(num/flog)*flog;
16 now=(num/flog)%10;
17 high=num/(flog*10);
18 switch (now)
19 {
20 case 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 }
30 flog=flog*10;
31 }
32 cout<<num<<"中出现数字1的个数为:"<<count<<endl;
33 return 0;
34 }
四:实验截图



五、实验总结
刚开始的时候我们的想法是找到一个通用的总结公式,但是在想了一段时间之后发现,这不是一个公式所能解决的,所以最好的方法就是找规律。在和同伴的不断总结之后,我们发现了规律,最终是实现了程序。
原文:http://www.cnblogs.com/myblog1993/p/4470368.html