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

来源:互联网 发布:淘宝延长收货设置 编辑:程序博客网 时间:2024/06/06 05:57

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

1):
对于:n=1230;
个位上为1的数有:0001,0011,0021,....1221,共123 * 1个数
            n=1231;
个位上为1的数有:0001,0011,0021,....1221,1231 共124 * 1 个数

            n=1233;

个位上为1的数有:0001,0011,0021,....1221,1231 共124 * 1 个数

2):

对于:n=1204;

十位上为1的数有:0010—0019;0110—0119;.....,1110—1119;共12*10 个数

对于:n=1214;

十位上为1的数字有:0010—0019;0110—0119;.....,1110—1119;1210/1211/1212/1213/1214;共12*10+4+1 个数

对于:n=1234;

十位上为1的数字有:0010—0019;0110—0119;.....,1110—1119;1210—1219;共(12+1) * 10 个数

所以有如下代码:

class Solution {public:    int NumberOf1Between1AndN_Solution(int n)    {        int tmp=n;        int nCurr=0;        int nBase=1;//处理到哪位上的数字了,个位(1)、十位(10)、百位(100)....        int total=0;        while(tmp!=0)        {            nCurr=tmp%10;            if(nCurr==0)            {                total+=(tmp/10)*nBase;            }            else if(nCurr==1)            {                total+=(tmp/10)*nBase+(n-tmp*nBase+1);            }            else            {                total+=(tmp/10+1)*nBase;            }            tmp=tmp/10;            nBase*=10;        }        return total;    }};




0 0
原创粉丝点击