暴力也能过?
运行3500+s
class Solution {
public int digitCounts(int k, int n) {
int result = 0;
String[] strs = new String[n + 1];
for (int i = 0; i <= n; i++) {
strs[i] = i + "";
result += findK(k, strs[i]);
}
return result;
}
public int findK(int k, String string) {
int result = 0;
String s = k + "";
char a = s.charAt(0);
for (int i = 0; i < string.length(); i++) {
if (a == string.charAt(i)) {
result++;
}
}
return result;
}
};
九章答案
运行4000+s
class Solution {
public int digitCounts(int k, int n) {
// write your code here
int cnt = 0;
for (int i = k; i <= n; i++) {
cnt += singleCount(i, k);
}
return cnt;
}
public int singleCount(int i, int k) {
if (i == 0 && k == 0)
return 1;
int cnt = 0;
while (i > 0) {
if (i % 10 == k) {
cnt++;
}
i = i / 10;
}
return cnt;
}
};