描述
计算数字 k 在 0 到 n 中的出现的次数,k 可能是 0~9 的一个值。
样例
样例 1:
输入:
k = 1, n = 1
输出:
1
解释:
在 [0, 1] 中,我们发现 1 出现了 1 次 (1)。
样例 2:
输入:
k = 1, n = 12
输出:
5
解释:
在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] 中,我们发现 1 出现了 5 次 (1, 10, 11, 12)(注意11中有两个1)。
本题是为了统计数字k(0~9)在0到n中出现的次数,首先我们以普通的情况来举例。若k=3,n=1234,要知道0-1234中包含多少个3,我们需要知道在3在1234的每一位上出现的次数。
先来看个位,3在个位上出现过多少次?因为1234的个位4>3,所以区间内个位出现3的数字有1233,1223,1213,1203,1193,········13,03;总共有(123-0+1)=124个。
再来看十位上,因为1234的十位3=3,所以区间内十位出现3的数字有1234,1233,1232,1231,1230,1139,1138,1137,1136,·······1130,1039,······,1030,······,39,·····,30;共有:((11-0+1)*10)+4-0+1=125个。
百位上,因为1234百位上2<3,所以区间内百位出现3的数字只有399,······,300;共有100个。
千位上,因为1234千位上1<3,所以区间内千位出现3的数字没有。
用cur来表示当前数字,aft来表示当前数字后面的数字,hea来表示当前数字的前面的数字。可以计算出目标数字k出现在当前位置的数字的个数在区间内有多少个,其中Math.pow(10, i)是当前位置的数量级,比如,当前位置是百位,那么Math.pow(10, i)=100;
if(cur>k)
count+=(hea+1)*Math.pow(10, i);
else if(cur==k)
count+=(hea)*Math.pow(10, i)+(aft)*Math.pow(10,0)+1;
else if(cur<k)
count+=(hea)*Math.pow(10, i);
下面粘上代码:
public class Solution
{
/**
* @param k: An integer
* @param n: An integer
* @return: An integer denote the count of digit k in 1..n
*/
public int digitCounts(int k, int n)
{
String str;
int count=0;
str=String.valueOf(n);
int level=str.length();//求出n的位数
int cur;
int aft;
int hea;
if (n<0)
return 0;
else if(k>=0&&n<10)
return 1;
else if(n>=10)
{
for(int i=0;i<level;i++)
{
cur=(int) (n/Math.pow(10, i)%10);
hea=(int) (n/(10*Math.pow(10, i)));
aft=(int) (n%Math.pow(10, i));
if(k==0)
{
if(i==level-1)//最高位不可能出现0
{ if(cur>k)
count+=(hea)*Math.pow(10, i);
else if(cur==k)
count+=(hea)*Math.pow(10, i)+(aft)*Math.pow(10, 0)+1;
else if(cur<k)
count+=(hea)*Math.pow(10, i);
}
else {
if(cur>k)
count+=(hea+1)*Math.pow(10, i);
else if(cur==k)
count+=(hea)*Math.pow(10, i)+(aft)*Math.pow(10,0)+1;
else if(cur<k)
count+=(hea)*Math.pow(10, i);
}
}
else {
if(cur>k)
count+=(hea+1)*Math.pow(10, i);
else if(cur==k)
count+=(hea)*Math.pow(10, i)+(aft)*Math.pow(10, 0)+1;
else if(cur<k)
count+=(hea)*Math.pow(10, i);
}
}
return count;
}
return 0;
}
}