You need to find which digit occurs most number of times across the four given input numbers.
input1, input2, input3 and input4 are the four given input numbers.
The program is expected to find and print the most frequent digit.
Example1 –
If input1=123, input2=234, input3=345, input4=673
We see that across these four numbers,
1, 5, 6 and 7 occur once,
2 and 4 occur twice, and
3 occurs four times.
Therefore, 3 is the most frequent digit and so the program must print 3
NOTE: If more than a digit occurs the same number of most times, then the smallest of those digits should be the result. Below example illustrates this.
Example2 –
If input1=123, input2=456, input3=345, input4=5043
We see that
0, 1, 2 and 6 occur once, and
3, 4 and 5 occur thrice.
As there are three digits (3, 4 and 5) that occur most number of times, the result will be the smallest (min) digit out of these three. Hence, the result should be 3
1
Expert's answer
2021-09-02T16:46:38-0400
import java.util.Scanner;
publicclass Main {
private static int[] digits = newint[10];
public static void splitNumber(int number) {
do {
digits[Math.abs(number % 10)]++;
number /= 10;
} while (number != 0);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int maxOccurs = 0;
int digit = 0;
System.out.print("Enter the first number: ");
int input1 = in.nextInt();
System.out.print("Enter the second number: ");
int input2 = in.nextInt();
System.out.print("Enter the third number: ");
int input3 = in.nextInt();
System.out.print("Enter the fourth number: ");
int input4 = in.nextInt();
splitNumber(input1);
splitNumber(input2);
splitNumber(input3);
splitNumber(input4);
for (int i = 0; i < digits.length; i++) {
if (digits[i] > maxOccurs) {
maxOccurs = digits[i];
digit = i;
} elseif (digits[i] == maxOccurs && digit > i) {
digit = i;
}
}
System.out.println("Max = " + digit);
}
}
"assignmentexpert.com" is professional group of people in Math subjects! They did assignments in very high level of mathematical modelling in the best quality. Thanks a lot
Comments