digit-counts
2015-11-02 13:35
232 查看
计算数字k在0到n中的出现的次数,k可能是0~9的一个值
您在真实的面试中是否遇到过这个题?
Yes
样例
例如n=12,k=1,在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],我们发现1出现了5次 (1, 10, 11, 12)
暴力解法:
线性时间复杂度O(n):
您在真实的面试中是否遇到过这个题?
Yes
样例
例如n=12,k=1,在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],我们发现1出现了5次 (1, 10, 11, 12)
暴力解法:
class Solution { public: int digitCounts(int k, int n) { int ans=0; for(int i=0;i<=n;i++){ ans+=count(i,k); } return ans; } int count(int num,int k){ string tmp=to_string(num); int res=0; for(int i=0;i<tmp.size();i++){ if(tmp[i]-'0'==k) res++; } return res; } };
线性时间复杂度O(n):
class Solution { public: /* * param k : As description. * param n : As description. * return: How many k's between 0 and n. */ int digitCounts(int k, int n) { // write your code here if(n==0){ return k==0?1:0; } int digits=0; int p=1; while(n>=p){ digits++; p*=10; } int back=0; int cur=n%10; int pre=n/10; int res=0; int cnt=1; while(cnt<=digits){ if(cur>k){ res+=(pre+1)*pow(10,cnt-1); }else if(cur==k){ res+=pre*pow(10,cnt-1)+back+1; }else{ res+=pre*pow(10,cnt-1); } back=cur*pow(10,cnt-1)+back; cur=pre%10; pre=pre/10; cnt++; } return k==0?res-10:res; } };
相关文章推荐
- 八皇后问题
- HelloWorld编程
- 修改linux最大连接数
- 选项菜单
- centos 编译 vlc-android
- GET请求和POST请求
- 错误笔记(1)——关于克隆虚拟机引发的后续问题
- Java 语言中 Enum 类型的使用介绍
- netfilter
- 高效率http retrofit2.0.2 最新版本
- 读《大道至简》第五章有感
- 泰勒公式与极值问题
- 数据库连接
- [CareerCup] 13.8 Smart Pointer 智能指针
- Android开发时图片Bitmap序列化问题(How to fix a java.io.NotSerializableException: android.graphics.Bitmap)
- 一个对前端模板技术的全面总结
- libpcap
- 关于弹出bootstrip的模态框示例
- 2015前端框架何去何从
- HDOJ 5532 Almost Sorted Array (正反LIS判断顺序)