# Program to Find Out the Occurrence of a Digit from a Given Range in Python

Suppose we have been provided with two positive integers n and d where d is a digit within 0 to 9. We have to determine how many times the digit d appears within the integer numbers between 1 and n.

So, if the input is like n = 45, d = 5, then the output will be 5.

These numbers have the digit 5: [5, 15, 25, 35, 45].

To solve this, we will follow these steps −

• Define a function solve(). This will take n and d as inputs.

• if n < 0, then

• return 0

• k := floor of (n /10) − 1

• ans := solve(k, d) * 10 + k + 1

• if d is same as 0, then

• ans := ans − 1

• m := floor of (n / 10) * 10

• while m <= n, do

• ans := ans + count of occurrences of string representation of d in string representation of m.

• m := m + 1

• return ans

• From the main function, now call the function −

• value := solve(n,d)

• print(value)

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, n, d):
if n < 0:
return 0
k = n // 10 − 1
ans = self.solve(k, d) * 10 + k + 1
if d == 0:
ans −= 1
m = n // 10 * 10
while m <= n:
ans += str(m).count(str(d))
m += 1
return ans
ob = Solution()
print(ob.solve(45,5))

## Input

45, 5

## Output

5