Created
April 12, 2016 20:14
-
-
Save cangoal/1761016cee54b868e5db5aeb8a4ff949 to your computer and use it in GitHub Desktop.
LintCode - Digit Counts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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