面试题43:从1到n整数中1出现的次数:O(logn)算法

/*

 * 面试题43:从1n整数中1出现的次数:O(logn)算法

 * 题目:求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?

 * 为此他特别数了一下1~13中包含1的数字有110111213因此共出现6,但是对于后面问题他就没辙了。

 * ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 n 1出现的次数)

 * 思路:考虑将n的十进制的每一位单独拿出讨论,每一位的值记为weight

 * weight0,则1出现次数为round*base

 * weight1,则1出现次数为round*base+former(该位之前的数)+1

 * weight大于1,则1出现次数为rount*base+base

 * 比如:

534 = (个位1出现次数)+(十位1出现次数)+(百位1出现次数)=53*1+1+5*10+10+0*100+100= 214

530 = 53*1+5*10+10+0*100+100 = 213

504 = 50*1+1+5*10+0*100+100 = 201

514 = 51*1+1+5*10+4+1+0*100+100 = 207

10 = (1*1)+(0*10+0+1) = 2

 */

 

public class No43NumberOf1Between1AndN_Solution {

 

    public static void main(String[] args) {

       No43NumberOf1Between1AndN_Solution n = new No43NumberOf1Between1AndN_Solution();

      System.out.println(n.NumberOf1Between1AndN_Solution(12));

 

    }

 

    public int NumberOf1Between1AndN_Solution(int n) {

       if (n < 1) {

           return 0;

       }

      

       int base = 1;

       int round = n;

       int count = 0;

      

       while (round > 0) {

           int weight = round % 10;

           round /= 10;

          

           count += round * base;

          

           if (weight == 1) {

              count += (n%base) + 1;

           } else if (weight > 1) {

              count += base;

           }

          

           base *=10;

       }

      

       return count;

    }

 

}

你可能感兴趣的:(面试题43:从1到n整数中1出现的次数:O(logn)算法)