Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

272
Visualizações
Writing the Java method for finding the most frequent digit in an int

I need help on this problem:

Write a method mostFrequentDigit that returns the digit value that occurs most frequently in a number. Example: The number 669260267 contains: one 0, two 2s, four 6es, one 7, and one 9. mostFrequentDigit(669260267) returns 6. If there is a tie, return the digit with the lower value. mostFrequentDigit(57135203) returns 3.

This is the code I have now, but it doesn't work:

public static int mostFrequentDigit(int num)
{
int largestCount = 0;
int currentCount = 0;
String num0 = Integer.toString(num)
 String mostFrequent = num0.substring(0,1);

for (int x = 0; x < num0.length(); x++)
{
        if (num0.substring(x,x+1).equals(mostFrequent))
        {
            currentCount++;
        }
        if (currentCount > largestCount)
        {
           largestCount = currentCount;
           mostFrequent = num0.substring(x,x+1);
        }
}
    return mostFrequent;

}
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You're going to have to keep track of the counts of all digits (e.g. in an array or Map) and get the result after you tallied all digits.

Here's an approach using an array:

public class MyClass {
    public static int mostFrequentDigit(int num) {
        int n = Math.abs(num);
        int digit = 0;
        int max = 0;
        int[] counts = new int[10];

        while (n != 0) {
            counts[n % 10]++;
            n /= 10;
        }

        for (int i = 0; i < counts.length; i++) {
            if (counts[i] > max) {
                digit = i;
                max = counts[i];
            }
        }

        return digit;
    }
    
    public static void main(String args[]) {
      System.out.println(mostFrequentDigit(57135203));
    }
}

This snippet uses a combination of modulo and integer division operations to get the separate digits, and for each digit increments the corresponding counter in an array. After everything is tallied, it traverses the array to find the digit with the highest counter.

over 4 years ago · Santiago Trujillo Relatório

0

There are some logical errors in your code. Provide a simple and short code to do this as below.

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

        public static int mostFrequentDigit(int num) {

        Map<String, Integer> map = new HashMap<String, Integer>();

        for (int i = 0; i < 10; i++) {
            String digit = String.valueOf(i);
            map.put(digit, StringUtils.countMatches(String.valueOf(num), digit));
        }

        Comparator<Map.Entry<String, Integer>> byValue = Map.Entry.comparingByValue();
        Map.Entry<String, Integer> maxEntry = Collections.max(map.entrySet(), byValue);

        return Integer.parseInt(maxEntry.getKey());
    }
over 4 years ago · Santiago Trujillo Relatório

0

Seems like school assignment problem. Your teacher definitely wants you to learn recursion.

So, collect data into array of size 10 (if you are computing for base 10 - you may do that same for base 16 for example)

Write recursive function (function which calls itself as long as it necessary ) which takes last digit of a number (modulo 10 in case of decimal digits) and passes rests of the number ( divided by 10, but as integer ) to next invocation of itself ( in case it is bigger than 0 )

After your recursion is terminated you have an array with counts for digits. Just process it with for loop and find index with maximal value

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda