剑指offer 32. 1到n整数中2出现的次数
2017-05-05 10:18
302 查看
//题目:从1到n个整数中输出2出现的次数 //解法1:同一每个数字中包含2的次数并相加 public class Main { public static void main(String[] args) throws Exception { System.out.println(get2Count(100)); } public static int get2Count(int n){ int i = 1; int result = 0; while(i<=n){ result = result+getNum(i); i++; } return result; } public static int getNum(int num){ int result = 0; while(num != 0){ if(num%10 == 2){ result++; } num = num/10; } return result; } } //解法2:按照数字位数出现的次数进行计算 public class Main { public static void main(String[] args) throws Exception { System.out.println(get2Count(100)); } public static int get2Count(int n){ String str = String.valueOf(n); return getNum(str); } public static int getNum(String str){ if(str == null || str.length() == 0){ return 0; } int length = str.length(); int first = str.charAt(0)-'0'; if(length == 1 && first>1){ return 1; } if(length == 1 && first<=1){ return 0; } int numFirst = 0; //第一位可能出现2的次数和两种可能 if(first>2){ numFirst = (int)Math.pow(10,length-1); }else if(first == 2){ numFirst = Integer.parseInt(str.substring(1))+1; } int numSecond = first*(length-1)*(int)Math.pow(10,length-2); //剩余位在第一位不变的情况下可能出现2的次数,其实就是全排列 int numIter = getNum(str.substring(1)); //将第一位删除,迭代执行程序 return numFirst+numSecond+numIter; } }
相关文章推荐
- 剑指offer 32---从1到n整数中1出现的次数
- 剑指offer--面试题32:整数中1出现的次数(从1到n整数中1出现的次数)
- 剑指Offer----面试题32:从1到n整数中1出现的次数
- 剑指Offer:面试题32:从1到n整数中1出现的次数
- 【九度OJ1373】|【剑指offer32】整数中1出现的次数(从1到n整数中1出现的次数)
- 剑指Offer面试题32(java版):从1到n整数中1出现的次数
- 剑指offer 32-从1到n整数中1出现的次数
- 剑指offer 面试题32—从1到n整数中1出现的次数
- 剑指Offer_面试题32_从1到n整数中1出现的次数(预留未解决)
- 剑指offer 32 整数中1出现的次数
- 剑指Offer面试题32(Java版):从1到n整数中1出现的次数
- 剑指Offer面试题31连续子数组的最大和,面试题32从1到n整数中1出现的次数
- 剑指offer 面试题32 从 1 到 n 整数中 1 出现的次数
- 【剑指offer-Java版】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出现的次数
- 剑指offer-5-面试32:从 1 到 n 整数中 1 出现的次数(时间效率)
- 【剑指offer】面试题32-从1到n整数中1出现的次数