从1到n整数中1出现的次数
来源:互联网 发布:网络直播平台赚钱吗 编辑:程序博客网 时间:2024/04/30 08:15
题目
输入一个整数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,有
对1到n内的数统计1的次数,时间复杂度就是
编程之美上讲解很详细,不想敲字了
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; }}
0 0
- 整数中1出现的次数(从1到n整数中1出现的次数)
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到 n整数中1出现的次数
- 从1到n整数中1出现的次数
- 大二下学习总结
- [Qt学习]14 Qt状态机框架——进入和退出状态
- 百度Map之Uncaught TypeError: Cannot read property 'fc' of undefined
- ARC MRC混编
- Josephus问题及其推广 分析和算法优化
- 从1到n整数中1出现的次数
- zh-cn:模板入门
- mybatis 中#与$的区别
- 服务器端脚本语言和客户端脚本语言
- BZOJ3174 [Tjoi2013]拯救小矮人
- CentOS6编译安装Nginx-1.8.1
- 纸牌游戏之三
- 理解 Objective-C Runtime
- BLE低功耗蓝牙关键技术解析与应用