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

356
Visualizações
Having trouble reading a simple recursion code(JAVA)

Hello I am studying recursion and having trouble reading the following code below

public class MysteryClass {

/**
 * Mystery method that performs a function recursively.
 *
 * @param x an integer > 0
 * @param y an integer > 0 and < x
 * prints result
 */
    public static void mysteryMethod(int x, int y) {
        if (x == 0) {
            return;
        } else {
            mysteryMethod(x / y, y);
            System.out.print(x % y);
        }
    }

    public static void main(String[] args) {
        mysteryMethod(13,2);
    }
}

I had two possible solutions(and realized both are wrong)

Solution 1

  1. x = 13, y = 2, print(13 % 2) which is 1
  2. x = 6 , y = 2, print( 6 % 2) which is 0
  3. x = 3 , y = 2, print( 3 % 2) which is 1
  4. x = 1 , y = 2, print( 1 % 2) which is 1
  5. x = 0 , y = 2, since x == 0, return nothing and stop recursion.

therefore 1011

Solution 2

  1. x = 13, y = 2, mysteryMethod(13 / 2, 2) which is mysteryMethod(6, 2) since 6 != 0 go to next step
  2. x = 6 , y = 2, mysteryMethod(6 / 2, 2) which is mysteryMethod(3, 2) since 3 != 0 go to next step
  3. x = 3 , y = 2, mysteryMethod(3 / 2, 2) which is mysteryMethod(1, 2) since 1 != 0 go to next step
  4. x = 1 , y = 2, mysteryMethod(1 / 2, 2) which is mysteryMethod(0, 2) since 0 == 0 return nothing and stop recursion.

therefore return nothing

but the correct answer was 1101

Can anyone have a look at the code and explain me why 1101 is the correct answer and why my solutions are wrong?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

That is because you did the recursion then print the number, you should print the number then recursion, that is:

public static void mysteryMethod(int x, int y) {
        if (x == 0) {
            return;
        } else {
            System.out.print(x % y);//exchange the position of the two lines of code
            mysteryMethod(x / y, y);
        }
    }

In you code, you're printing the number backward...

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