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

来源:互联网 发布:淘宝争议处理规范2016 编辑:程序博客网 时间:2024/06/06 10:55

publicclass Q32 {   /**    * 题目:从1到n整数中1出现的次数    * 题目说明:输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。例如输入12,从1到12这些整数中包含1的数字有1,10,11,12,1一共出现5次。    * 解题思路(1):利用基本的方法来做,但效率不高。遍历每个数字,然后统计每个数字中1的个数。    * 解题思路(2):利用拆分的方法,来统计整数中的1的个数。其时间复杂度由于思路(1)。    */   publicstatic void main(String[] args) {      Q32 test = new Q32();      System.out.println(test.theNumbersOf1FromN(123));      System.out.println(test.theNumberOf1FromN2(123));   }   //思路(1)   publicint theNumbersOf1FromN(int n){      int number = 0;      for(int i = 1; i <= n; i++){//遍历从1到n的所有元素         number += NumberOf1(i);      }      return number;   }   publicint NumberOf1(int n){//统计一个数字元素中1的个数      int count = 0;      while(n != 0){         if(n % 10 == 1){            count ++;         }         n = n / 10;      }      return count;   }   //思路(2)   publiclong theNumberOf1FromN2(int n){      long count = 0;      long i = 1;      long current = 0, high = 0, low = 0;      while((n / i) != 0){         current = (n / i) % 10;//当前位数字,比如输入123,(1)则current为3   (2)current为2 (3)current为1         high = n / (i * 10);//高位中1的情况,          则high为12       high为1        high为0         low = n - (n / i) * i;//低位中1的情况                             则low为0         low为3         low为23         if(current > 1){            count = count + (high + 1) * i;//高位中含有1的个数 (1) 0+(12+1)*1=13 (2)13+(1+1)*10=33         }elseif(current == 0){            count = count + high * i;         }elseif (current == 1) {            count = count + high * i + low+1; //(3)33+0*i+23+1=57         }         i = i * 10;      }      return count;   }}


0 0