从1到n整数中1出现的次数
2016-06-27 22:02
148 查看
题目
输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。例如输入12,从1到12这些整数中包含1的数字有1,10,11,12共出现5次解题
这个题目比较难直接暴力
public class Solution { public int NumberOf1Between1AndN_Solution(int n) { int count = 0; for(int i =1;i<=n;i++){ count +=NumberOf1(i); } return count; } public int NumberOf1(int num){ int count =0; while(num!=0){ if(num%10==1){ count++; } num/=10; } return count; } }
对数字n,有log(n)位
对1到n内的数统计1的次数,时间复杂度就是nlog(n)
编程之美上讲解很详细,不想敲字了
public class Solution { public int NumberOf1Between1AndN_Solution(int n) { int count = 0; int factor = 1; int low = 0; int cur = 0; int high = 0; while(n/factor!=0){ cur = (n/factor)%10; //当前位 low = n - (n/factor)*factor ;// 低位数字 high = n/(factor*10); //更高位 switch( cur){ case 0: count+= high* factor; break; case 1: count+= high* factor + low + 1; break; default: count +=(high+1) * factor; break; } factor *=10; } return count; } }
相关文章推荐
- android中activity启动模式
- Mapbox简易入门教程
- 【GOF23设计模式】_解释器模式_访问者模式_数学表达式动态解析库式JAVA247
- 安卓消息处理机制(Looper,Handler,Message)
- 适合程序员的四大字体
- 常见的缓存算法设计策略
- Linux的notifier机制在TP中的应用
- Java构造器的优化
- 常见的缓存算法设计策略
- Theano 配置GPU出错:g++: error trying to exec 'cc1plus': No such file or directory
- linux----->shell高级编程----grep应用
- 五大常用算法——分治法,动态规划,回溯法,分支界限法,贪心算法
- 2.5.4 进程同步,互斥的区别和联系
- (OK)(OK) Creating VMs from an existing VDI file in CLI (VBoxManage) in Fedora 23
- 循环队列
- 浮动【电梯】或【回到顶部】小插件:iElevator.js
- sqlite3---The database file is locked
- Number of Islands (孤岛的数量)
- Swift中单例的实现方法
- 欧几里德与扩展欧几里德算法