lintcode 中等题:digits counts 统计数字

时间:2023-03-09 09:48:32
lintcode 中等题:digits counts 统计数字

题目

计算数字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)

解题

暴力,余数是否等于k。

class Solution {
/*
* param k : As description.
* param n : As description.
* return: An integer denote the count of digit k in 1..n
*/
public int digitCounts(int k, int n) {
// write your code here
int count = 0;
for(int i = 0 ;i <= n ; i ++){
int m = i;
if(m==0&&k==0){
count+=1;
}else{
while(m!=0){
if(m%10==k){
count++;
}
m=m/10;
}
} }
return count;
}
};

Java Code

总耗时: 2487 ms

class Solution:
# @param k & n two integer
# @return ans a integer
def digitCounts(self, k, n):
count = 0
for i in range(n+1):
l = list(str(i))
count+=l.count(str(k))
return count

Python Code

总耗时: 404 ms

Python 直接list后统计k出现的次数,貌似更简单了