Algorithm
Problem Name: 2 AD-HOC - beecrowd | 2138
Problem Link: https://www.beecrowd.com.br/judge/en/problems/view/2138
Most Frequent Digit
By Joao Marcos Salvanini Bellini de Moraes, IFSULDEMINAS Brazil
Timelimit: 1
In Nlogonia, several programmers participate in a cryptography competition named "Decrypt it!", in which the one who decrypt more messages wins.
In the middle of the competition, you notice that to continue and decrypt a message, you must solve the following challenge: find the most frequent digit of a number with up to 1001 digits.
Input
The input consists of several lines, containing an integer N (1 ≤ N ≤ 101000). Read input until EOF.
Output
Print the most frequent digit of the given number. If there's more than one, print the greatest one among them.
Input Sample | Output Sample |
3981152060 1508442812980080428167730232746481 |
1 8 |
Code Examples
#1 Code Example with C Programming
Code -
C Programming
#include <stdio.h>
#include <string.h>
short charToInt(char numero);
int main (void)
{
char numero, numerosStr[1110] = { 0 };
short numeros[1110] = { 0 };
short i, posiMaior, maior;
while (scanf(" %s", numerosStr) != EOF)
{
for (i = 0; numerosStr[i]; i++)
numeros[charToInt(numerosStr[i])]++;
posiMaior = 0;
maior = numeros[0];
for (i = 1; i < 1110; i++)
if (numeros[i] >= maior && posiMaior < i)
{
posiMaior = i;
maior = numeros[i];
}
printf("%hu\n", posiMaior);
memset(numeros, 0, sizeof(numeros));
memset(numerosStr, 0, sizeof(numerosStr));
}
}
short charToInt(char numero)
{
return (numero - 48);
}
Copy The Code &
Try With Live Editor
Input
1508442812980080428167730232746481
Output
8
#2 Code Example with C++ Programming
Code -
C++ Programming
#include <cstdio>
#include <cstring>
int frequencia[1000];
char entrada[100010];
int main() {
while (scanf("%s", entrada) != EOF) {
int tamanho = strlen(entrada), maximo = 0;
char resposta = '0';
memset(frequencia, 0, sizeof(frequencia));
for (int i = 0; i < tamanho; i++) {
frequencia[entrada[i]]++;
}
for (char digito = '0'; digito < = '9'; digito++) {
if (frequencia[digito] >= maximo) {
maximo = frequencia[digito];
resposta = digito;
}
}
printf("%c\n", resposta);
}
return 0;
}
Copy The Code &
Try With Live Editor
Input
1508442812980080428167730232746481
Output
8
#3 Code Example with Python Programming
Code -
Python Programming
def stol(s):
return [int(c) for c in s]
while True:
try:
s=stol(input())
f=set(s)
d=dict()
for x in f:
d[x]=s.count(x)
d=dict(sorted(d.items(), key=lambda item: item[0],reverse=True))
d=dict(sorted(d.items(), key=lambda item: item[1],reverse=True))
for i,j in d.items():
print(i)
break
except EOFError:break
Copy The Code &
Try With Live Editor
Input
1508442812980080428167730232746481
Output
8