- /**
- * 计算1~limit之间,总共1出现的次数 如 1~13 1出现的次数是6
- */
- static void total1times(int limit){
- int current=0;//当前位
- int height=0;//高位
- int lower=0;//低位
- int count=0;//总记录数
- int factor=1;//需要计算1出现的次数 (因数)
- while(limit/factor!=0){
- lower=limit-(limit/factor)*factor;//低位
- current=(limit/factor)%10;//计算当前位数
- height=limit/(factor*10);//计算高位
- switch(current){
- case 0://如果当前位上的数==0 ,则 count=最高位*因数 如 12013 = 12*100
- count+=height*factor;
- break;
- case 1://如果当前位上的数==0 ,则 count=最高位*因数 如 12113 = 12*100+114 114=(100~113)
- count+=height*factor+lower+1;
- break;
- default://否则说明>1 则是最高位+1 *因数
- count+=(height+1)*factor;
- break;
- }
- factor*=10;
- }
- System.out.println("1~"+limit+"之间1出现的次数为: "+count);
- }
- /**
- * 解题步骤:
- * 如:115
- * 先将数分解为 高位,当前位,低位
- * 按一定的规则计算,1出现次数与当前位上的数之间的关系 从《编程之美》章节 [1的数目] 中领悟如下
- *
- * (1):当前位上的数字=0时 ,1出现的次数=高位*当前位+低位+1
- * (2):当前位上的数字=1时,1出现的次数=高位*当前位+低位+1
- * (3):当前位上的数字>1时,1出现的次数=高位+1*当前位
- * 如,一开始 115的当前位是 5 高位是11 低位是 0
- * 5>1 则按规则3 为 11+1*1(1为当前位)=12
- * 循环到第二次 当前位是 1 高位是1 低位是 1
- * 1==1 则按规则2 为 1*10+5+1=16
- * 循环到第三次 当前位是 1 高位是0 低位是 15
- * 1==1 则按规则2 为 0*100+15+1=16
- *
- * 则最终结果为 个位出现1的次数 + 十位出现1的次数 + 百位出现1的次数 12+16+16=44
- */