1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution: def numberOfBeautifulIntegers(self, low: int, high: int, k: int) -> int: def calc(high: int) -> int: s = str(high) @cache def dfs(i: int, val: int, diff: int, is_limit: bool, is_num: bool) -> int: if i == len(s): return int(is_num and val == 0 and diff == 0) res = 0 if not is_num: res = dfs(i + 1, val, diff, False, False) d0 = 0 if is_num else 1 up = int(s[i]) if is_limit else 9 for d in range(d0, up + 1): res += dfs(i + 1, (val * 10 + d) % k, diff + d % 2 * 2 - 1, is_limit and d == up, True) return res return dfs(0, 0, 0, True, False) return calc(high) - calc(low - 1)
|