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
#include <iostream>
#include <string>
using namespace std;
int main()
{
int input1, input2, input3, input4;
int arr[100];
int arrsize, temp_most = arr[0];
int max_freq = 0, most_element = 9, freq = 0;
cout<<"Enter input 1: ";
cin>>input1;
cout<<"Enter input 2: ";
cin>>input2;
cout<<"Enter input 3: ";
cin>>input3;
cout<<"Enter input 4: ";
cin>>input4;
string s1 = to_string(input1),
s2 = to_string(input2),
s3 = to_string(input3),
s4 = to_string(input4),
s5 = s1 + s2 + s3 + s4;
arrsize = s1.length() + s2.length() + s3.length() + s4.length();
for(int i = 0; i < arrsize; i++){
arr[i] = s5[i] - '0';
}
for(int i = 0; i < arrsize; i++){
freq = 0;
for(int j = 0; j < arrsize; j++){
if(arr[i] == arr[j]){
freq++;
}
}
if(freq > max_freq){
max_freq = freq;
most_element = arr[i];
}
if(freq == max_freq){
temp_most = arr[i];
if(temp_most < most_element)
most_element = temp_most;
}
}
cout<<"The most occuring digit is "<<most_element;
return 0;
}
Comments
Leave a comment