2013年大众点评网的一道程序笔试题
2013-05-30 16:32
295 查看
输入任意正整数n,统计1到n中1出现的次数,比如输入12,其中1,10,11,12出现了5次。
我知道的两种c++实现算法如下,写在一起比较起来方便:
应该也没有比第二种更快的算法了,因为已经超过了int的最大值,用double测试的结果都基本上运行时间为0
我知道的两种c++实现算法如下,写在一起比较起来方便:
#include <iostream> #include <sstream> #include <string> #include <time.h> using namespace std; void main(){ clock_t start1,start2,end1,end2; double n; cin>>n; start1 = clock(); int count = 0; for(int i = 1;i <= n;i++){ string nStr = to_string(i); int pos = nStr.find_first_of('1'); if( pos != string::npos) { count++; for(;nStr.find_first_of('1',pos + 1) != string::npos; count++, pos = nStr.find_first_of('1', pos + 1)); } } end1 = clock(); cout<<count<<" run time:"<<end1 - start1<<endl; start2 = clock(); int length=0,sum=0; int number=n; while(number>0) { number/=10; length++; } for(int i=1;i<=length;i++) { sum+=(int) (n / pow(10,i)) * pow(10,i-1); int tmp=(int)(n/pow(10,i-1))%10; if(tmp>1) sum+=pow(10,i-1); if(tmp==1) sum+=int(n)%(int)(pow(10,i-1))+1; } end2 = clock(); cout<<sum<<" run time:"<<end2 - start2<<endl; }
应该也没有比第二种更快的算法了,因为已经超过了int的最大值,用double测试的结果都基本上运行时间为0
相关文章推荐
- 2013年大众点评网笔试题,输入任意正整数n,统计1到n中1出现的次数
- 2013年阿里巴巴一道笔试题(大文件处理)
- 2013年阿里巴巴一道笔试题(大文件处理)
- 分享一道百度笔试程序题
- 百度2013年校园招聘一道笔试题--三位密码组合问题递归求解
- 阿里巴巴一道笔试题【程序中错误量的估算】
- 格子取数问题 2013年搜狗的校招笔试题 专业程序代写
- 一道关于sizeof()的困惑的笔试题
- C++及Windows异常处理(try,catch; __try,__finally; __try, __except)——一道笔试题引起的探究
- 一道关于java线程中断的题目,求大神指导,昨晚的阿里巴巴笔试题
- 2013年海康威视校园招聘笔试题
- 大华股份的一道笔试题 C/C++
- 《C和指针》上的一道读取、打印字符的简单程序
- 一张图解决一道笔试题 --- 理解fork函数
- 关于位运算的一道笔试题
- 一道关于下标排序的金山笔试题
- 一道网上找的微软笔试题
- 字符串唯一前缀问题;一道Trie树笔试题;
- C++并发实战:面试题2:一道迅雷笔试题
- 2013年小米校园招聘笔试题