InterviewSolution
Saved Bookmarks
| 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: 142454Output: The digit 4 occurs 3 times in 142454
|
|