Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created April 12, 2016 20:14
Show Gist options
  • Select an option

  • Save cangoal/1761016cee54b868e5db5aeb8a4ff949 to your computer and use it in GitHub Desktop.

Select an option

Save cangoal/1761016cee54b868e5db5aeb8a4ff949 to your computer and use it in GitHub Desktop.
LintCode - Digit Counts
// solution 1
public int digitCounts(int k, int n) {
// write your code here
if(k < 0 || n < 0) return 0;
if(k == 0 && n == 0) return 1;
int factor = 1, count = 0;
while(factor <= n){
int low = n % factor;
int high = n / (10 * factor);
int digit = n / factor % 10;
if(digit == k){
count += high * factor + (k == 0 && high == 0 ? 0 : (low + 1));
} else if(digit < k) {
count += high * factor;
} else if(digit > k){
count += high * factor + (k == 0 && high == 0 ? 0 : factor);
}
factor *= 10;
}
return count;
}
// solution 2
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment