数字统计:计算数字k在0到n中的出现的次数,k可能是0~9的一个值
样例:例如n=12,k=1,在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],我们发现1出现了5次(1, 10, 11, 12)
1、Python
class Solution:
"""
@param: : An integer
@param: : An integer
@return: An integer denote the count of digit k in 1..n
""" def digitCounts(self, k, n):
# write your code here
sum = 0
k=str(k)
for i in range(n + 1):
s = str(i)
for j in s:
if(j==k):
sum+=1
return sum
2、Java
说明:
设一个整数为abcdef(六位数),current表示当前正在统计的i位上的数字大小(i=10时,current=e i=1000时,current=c)
before为current之前的所有数字,after为current之后的所有数字(current=d时,before=abc,after=ef)
举例:
534898 current=4 before=53 after=898
从个位开始统计。直到统计完所有位。
public class Solution {
/*
* @param : An integer
* @param : An integer
* @return: An integer denote the count of digit k in 1..n
*/
public int digitCounts(int k, int n) {
// write your code here
int current = 0,before = 0,after = 0;
int i = 1,count = 0;
int flag=1;
while(n/i != 0 || (n==0&&flag==1)){//n=0,k=0特殊情况处理
if(n==0){
flag=0;
}
current = (n / i) % 10;
before = n / (i * 10);
after = n - before * (i * 10) - current * i;
if(k!=0 || before!=0){
if(current > k)
count += (before + 1) * i;
else if(current < k)
count += before * i;
else
count += before * i + after + 1;
}
else{
if(after!=0)
count += 0;
else
count += 1;
}
i *= 10;
}
return count;
}
};