加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

从1到n整数中1出现的次数

发布时间:2020-12-13 21:10:14 所属栏目:PHP教程 来源:网络整理
导读:题目 输入1个整数n,求从1到n这n个整数的10进制表示中1出现的次数。例如输入12,从1到12这些整数中包括1的数字有1,10,11,12共出现5次 解题 这个题目比较难 直接暴力 public class Solution { public int NumberOf1Between1AndN_Solution ( int n) { int cou

题目

输入1个整数n,求从1到n这n个整数的10进制表示中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; } }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读