Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Python program to count number of times x digit occurs in each and every number from 0 to n

Number of times x digit occurs in each number from 0 to n

 
In this python program, we will be counting the occurrence of a single digit in a number or from a group of digits. The number can be of any length starting from one to infinity, and Number can be ranging between -infinity to +infinity if we talk about numbers only. Other than these numbers can be divided into different groups like:
 
  • Whole Number
  • Natural Number
  • Rational Number
  • Real Number
 
Etc. In this case, we will be counting the occurrence of a digit in a number without being specific to its type and its range.
Python program to count number of times x digit occurs in each and every number from 0 to n

Algorithm

  • Step 1:- Start.
  • Step 2:- Take input from the user.
  • Step 3:- Take input of a digit whose occurrence is to be found.
  • Step 4:- Change the datatype of the integer inputs.
  • Step 5:- use the count function to count the occurrence of the digit and print it.
  • Step 6:- End.

Python Program for occurrence of a Digit

#take user inputs
Number = int(input('Enter the Number :'))
Digit = (int(input('Enter the digit :')))
#initialize Strings
String1 = str()
String2 = str()
#typecast int to str
String1 = str(Number)
String2 = str(Digit)
#count and print the occurrence
#Count function will return int value 
#so change it's type to string and concatenate it
print('Digit count is :'str(String1.count(String2)))
Output
Enter the Number :897982
Enter the digit :9
Digit count is :2

One comment on “Python program to count number of times x digit occurs in each and every number from 0 to n”


  • Om Prakash

    Code in Java :
    import java.util.Scanner;
    public class Frequency_of_Digit
    { public static void main(String[] args)
    {
    Scanner sc = new Scanner(System.in);
    System.out.print(“Enter number: “);
    String number = sc.nextLine();
    System.out.print(“Enter digit: “);
    char digit = sc.nextLine().charAt(0);
    sc.close();
    int count=0;
    for(int i=0; i<number.length(); i++)
    if(number.charAt(i)==digit)
    count++;
    System.out.println(count);
    }
    }