1.

Write a program in Java to calculate the number of times a digit ‘D’ appears in a number N. You have to take N and D as inputs from the user.

Answer»

This is the follow-up question to the previous question. In the previous question, we discussed how you can check the value of a digit using the modulus (%) operator. So, we will just use the previous code and in every iteration, we will check whether the digit is “D” or not. If it is D, increment the counter. The program for the same is shown below:

Java Code for Calculating Frequency of a Digit D in a Number N

import java.util.*;
class Main {

public static int countDigitFreq(int n,int D) {
if(n == 0 && D == 0) return 1; //number 0 has 1 frequency of 0

//if a negative number is entered
if(n < 0) n = -n;

int counter = 0;
while(n != 0) {
int digit = n % 10; //calculate the digit
if(digit == D) counter++;
n = n/10;
}

return counter;
}

public static void main(String args[]) {
// Your code goes here
Scanner scn = new Scanner(System.in);
int n = scn.nextInt(); //input the number
int d = scn.nextInt(); //input the digit

int x = countDigitFreq(n,d);
System.out.println("The digit " + d + " occurs " + x + " times in " + n);
}
}

Sample Input/Output

Input: 142454
Output: The digit 4 occurs 3 times in 142454


  • Corner Cases You Might Miss: If the input number is 0 and the digit is also 0, it becomes a crucial corner case. This is because the number 0 has 1 frequency of digit 0 but it will not be handled correctly by our loop. So, we do this separately. Also, we have converted the negative numbers to positive ones to solve this problem.


  • Time Complexity: O(log10N) where N is the input number. This is because we keep dividing the number by 10.


  • Auxiliary Space: We have not used any auxiliary Space here. So, it is O(1).




Discussion

No Comment Found