LeetCode 1067. Digit Count in Range Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
1067. Digit Count in Range

Description

Given a single-digit integer d and two integers low and high, return the number of times that d occurs as a digit in all integers in the inclusive range [low, high].

 

Example 1:

Input: d = 1, low = 1, high = 13
Output: 6
Explanation: The digit d = 1 occurs 6 times in 1, 10, 11, 12, 13.
Note that the digit d = 1 occurs twice in the number 11.

Example 2:

Input: d = 3, low = 100, high = 250
Output: 35
Explanation: The digit d = 3 occurs 35 times in 103,113,123,130,131,...,238,239,243.

 

Constraints:

  • 0 <= d <= 9
  • 1 <= low <= high <= 2 * 108

Solutions

Solution 1

PythonJavaC++Go
class Solution: def digitsCount(self, d: int, low: int, high: int) -> int: return self.f(high, d) - self.f(low - 1, d) def f(self, n, d): @cache def dfs(pos, cnt, lead, limit): if pos <= 0: return cnt up = a[pos] if limit else 9 ans = 0 for i in range(up + 1): if i == 0 and lead: ans += dfs(pos - 1, cnt, lead, limit and i == up) else: ans += dfs(pos - 1, cnt + (i == d), False, limit and i == up) return ans a = [0] * 11 l = 0 while n: l += 1 a[l] = n % 10 n //= 10 return dfs(l, 0, True, True)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !