《剑指offer》-任意非负整数区间中1出现的次数
2018-01-27 14:22
218 查看
/* * 求出1~13的整数中1出现的次数,1~13中包含1的数字有1、10、11、12、13,因此共出现6次, * 很快的求出任意非负整数区间中1出现的次数。 */ public class NumberOf1Between1AndN_Solution { //将数字转化成字符串,判断字符串中包含多少个1 public int numberOf1Between1AndN_Solution(int n) { int count = 0; for(int i = 1;i <= n;i ++) { String str = String.valueOf(i); for(int j = 0;j < str.length();j ++) { if(str.charAt(j) == '1') { count ++; } } } return count; } /*数字不断对10取余,判断余数是否为1 *注:如果有n个数,则整体算法复杂度O(nlogn)以10为底 */ public int numberOf1Between1AndN_Solution2(int n) { int count = 0; for(int i = 1;i <= n;i ++) { int temp = i; while(temp != 0) { if(temp % 10 == 1) { count ++; } temp = temp / 10; } } return count; } public static void main(String[] args) { System.out.println(new NumberOf1Between1AndN_Solution().numberOf1Between1AndN_Solution2(13)); } }
相关文章推荐
- 求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数。
- 求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数。
- Java求任意非负整数区间中1出现的次数
- hdu 1806 Frequent values(给定一个非降序数组,求任意区间内出现次数最多的数的次数)
- 《剑指offer》-数字在排序数组中出现的次数
- 剑指offer-面试题29-数组中出现次数超过一半的数字
- 在排序数组中找给定数字出现的次数和任意整数有几种分解方法
- 剑指offer——面试题32:从1到n整数中1出现的次数
- 计算数值区间内某个数字出现的次数
- 求一个区间[a,b]中数字1出现的次数
- 《剑指Offer》数组中出现次数超过一半的数字
- 剑指offer(四十)之整数中1出现的次数(从1到n整数中1出现的次数)
- 《剑指offer》面试题32----从1到n整数中1出现的次数
- 剑指Offer面试题29(java版):数组中出现次数超过一半的数字
- java---计算出现次数最大的任意字符
- 剑指offer系列之二十七:数组中出现次数超过一半的数
- 【剑指offer系列】 数字在排序数组中出现的次数___38
- 剑指Offer(Java版):数字在排序数组中出现的次数
- 剑指offer(二十四)之数组中出现次数超过一半的数字
- 剑指Offer:指定数字在排序数组中出现的次数