剑指offer 面试题32—从1到n整数中1出现的次数
来源:互联网 发布:云计算相关股票有哪些 编辑:程序博客网 时间:2024/06/05 18:42
题目:
输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。
例如输入12,从1到12这些整数中包含1的数字有1,10,11,12。所以1一共出现了5次。
解法一:O(nlogn)
基本思想:
累加1到n每个整数中1出现的次数。n个数,每个数有O(logn)位。
#include <iostream>using namespace std;int numberof1(int n){int ret=0;while(n){if(n%10==1)ret++;n/=10;}return ret;}int foo(int n){int count=0;for(int i=1;i<=n;i++)count+=numberof1(i);return count;}int main(){int n;while(cin>>n){cout<<foo(n)<<endl;}return 0;}
解法二:O(logn)
输入n有O(logn)位。
基本思想:数字规律
#include <iostream>using namespace std;int foo(int n){int icount=0;int iflag=1;int ilow=0;int icurr=0;int ihigh=0;while(n/iflag!=0){ilow=n-(n/iflag)*iflag;icurr=(n/iflag)%10;ihigh=n/(iflag*10);switch(icurr){case 0:icount+=ihigh*iflag;break;case 1:icount+=ihigh*iflag+ilow+1;break;default:icount+=(ihigh+1)*iflag;break;}iflag*=10;}return icount;}int main(){int n;while(cin>>n){cout<<foo(n)<<endl;}return 0;}
0 0
- 剑指offer 面试题32—从1到n整数中1出现的次数
- [剑指offer][面试题32]从1到n整数中1出现的次数
- 剑指Offer:面试题32 从1到n整数中1出现的次数
- 剑指offer-面试题32:从1到n整数中1出现的次数
- 算法 剑指Offer 面试题32 从1到n整数中1出现的次数
- 剑指Offer----面试题32:从1到n整数中1出现的次数
- 剑指offer面试题 32:从 1 到 n 整数中 1 出现的次数
- 剑指offer面试题32:从1到n整数中1出现的次数
- 【剑指offer】面试题32-从1到n整数中1出现的次数
- 剑指Offer系列-面试题32:从1到n整数中1出现的次数
- 剑指offer 面试题32 从 1 到 n 整数中 1 出现的次数
- 剑指offer-面试题32-从1到n整数中1出现的次数
- 剑指offer面试题[32]:从1到n整数中1出现的次数
- 【剑指Offer】面试题32:从1到n整数中1出现的次数
- 剑指Offer:面试题32:从1到n整数中1出现的次数
- 【剑指offer】5.2时间效率——面试题32:从1到n整数中1出现的次数
- 剑指Offer:面试题32——从1到n整数中1出现的次数(java实现)
- 剑指Offer:面试题32——从1到n整数中1出现的次数(java实现)
- rails 为表添加1列
- C++数组。
- .nil? , .empty?, .blank? .present? 的区别
- when you start Windows 7: "The Windows Boot Configuration Data file is missing required information"
- unity3D技术之WaitForEndOfFrame 等待帧结束
- 剑指offer 面试题32—从1到n整数中1出现的次数
- 史上一流的好书都在这里!
- pwd
- Android开发优化系列之使用软引用和弱引用
- linux expect 实例
- vector初始化
- 用不同的SQL语句查出多个结果存入一个数据集的同一个字段的代码例子
- 设置文件权限
- spring几个常用注解