- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

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

- Related Articles
- Program to find out the number of special numbers in a given range in Python
- Program to remove last occurrence of a given target from a linked list in Python
- Program to find out the value of a given equation in Python
- Program to find out the greatest subarray of a given length in python
- Python Program to find out the determinant of a given special matrix
- Python program to find occurrence to each character in given string
- Python program to extract characters in given range from a string list
- Program to find bitwise AND of range of numbers in given range in Python
- C++ program to find number in given range where each digit is distinct
- Program to find last digit of the given sequence for given n in Python
- Program to find out number of distinct substrings in a given string in python
- Program to find out special types of subgraphs in a given graph in Python
- C++ Program to find the smallest digit in a given number
- Python Program to find out the number of sets greater than a given value
- Program to find out is a point is reachable from the current position through given points in Python