整数中1出现的次数(从1到n整数中1出现的次数)

 题目描述:求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13.
因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数。

/*解题思路:编程之美上的:
*计算从右边数第i位包含的X的个数时:
*1.取第i位左边的(即高位,不止一个数字)数字H,H*10i-1=a;
*2.去第i位数字,判断
* (1)如果大于X,则结果为a+low+1;
* (2)如果小于X,则结果为a;
* (3) 如果等于X,则结果为a+10i-1;
*/

public int NumberOf1Between1AndN_Solution(int n) {
        if(n<0) return 0;
        int high=n,temp,cur,low=0;
        int i=1;
        int total=0;
        while(high!=0){
            high=n/(int)Math.pow(10, i);//获得右数第i位的高位数字
            temp = n%(int)Math.pow(10, i);//获取包括第i位及其以后位的数字
            cur = temp/(int)Math.pow(10, i-1);//获取当前位的值
            low = temp%(int)Math.pow(10, i-1);//获取地位数字
            if(cur==1){
                total+=high*(int)Math.pow(10, i-1)+low+1;
            }else if(cur<1){
                total+=high*(int)Math.pow(10, i-1);
            }else{
                total+=(1+high)*(int)Math.pow(10, i-1);
            }
            i++;
        }
        return total;
    }
原文地址:https://www.cnblogs.com/tjuxqcui/p/5539238.html