2020-04-13 11:38:31
Problem Description:
Given an integer n, count the number of occurrences of the number 1 in all non-negative integers less than or equal to n.
Example:
Input: 13
Output: 6
Explanation: The number 1 appears in the following numbers: 1, 10, 11, 12, 13.
Problem solving:
Digital dp can be used for efficient solution.
dp [pos] [cnt]: A total of cnt 1s appear before the current digit, and the total number of 1s that can be obtained.
int[] digits = new int[64]; int[][] dp = new int[64][64]; public int countDigitOne(int n) { if (n <= 0) return 0; int pos = 0; while (n > 0) { digits[pos++] = n % 10; n /= 10; } return dfs(pos - 1, 0, true); } public int dfs(int pos, int cnt, boolean limit) { if (pos == -1) return cnt; if (!limit && dp[pos][cnt] != 0) return dp[pos][cnt]; int up = limit ? digits[pos] : 9; int res = 0; for (int i = 0; i <= up; i++) { res += dfs(pos - 1, cnt + (i == 1 ? 1 : 0), limit && i == up); } if (!limit) dp[pos][cnt] = res; return res; }