剑指offer 32. 1到n整数中2出现的次数
来源:互联网 发布:域名注册机构有哪些 编辑:程序博客网 时间:2024/06/05 02:42
//题目:从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;}}
0 0
- 剑指offer 32. 1到n整数中2出现的次数
- 剑指offer-面试题32.从1到n整数中1出现的次数
- 《剑指offer》整数中1出现的次数(从1到n整数中1出现的次数)
- 剑指offer--整数中1出现的次数(从1到n整数中1出现的次数)
- 剑指Offer--032-整数中1出现的次数(从1到n整数中1出现的次数)
- [剑指offer]整数中1出现的次数(从1到n整数中1出现的次数)
- 剑指offer-整数中1出现的次数(从1到n整数中1出现的次数)
- 剑指Offer:整数中1出现的次数(从1到n整数中1出现的次数)
- 剑指offer:整数中1出现的次数(从1到n整数中1出现的次数)
- 剑指offer----整数中1出现的次数(从1到n整数中1出现的次数)
- 剑指offer-整数中1出现的次数(从1到n整数中1出现的次数)
- 剑指offer 整数中1出现的次数(从1到n整数中1出现的次数)
- 剑指offer-31.整数中1出现的次数(从1到n整数中1出现的次数)
- 【剑指offer】整数中1出现的次数(从1到n整数中1出现的次数)
- 《剑指offer》整数中1出现的次数(从1到n整数中1出现的次数)
- 剑指offer:整数中1出现的次数(从1到n整数中1出现的次数)
- 整数中1出现的次数,即从1到n整数中1出现的次数(剑指Offer)
- 【剑指offer-Java版】32从1到n的整数中1出现的次数
- jq 获取用户选择的:性别,所在地 等
- AngularJs:Directive指令用法
- EOS中在java代码中直接访问逻辑流
- IOS调试正常,打包闪退
- 条件注释判断浏览器<!--[if !IE]><!--[if IE]><!--[if lt IE 6]><!--[if gte IE 6]>
- 剑指offer 32. 1到n整数中2出现的次数
- SSD(Single Shot MultiBox Detector):绘制训练过程loss,accuracy曲线
- 弹簧动画-----Spring Animation
- MFC库参考
- 如何创建自定义 logger 格式化?
- javascript循环遍历数组输出key value
- linux命令之init
- 学习hibernate笔记
- 外资云服务进驻中国,对现有格局会有何影响?