LearnFrenzy
Sign in Take a free test

Methods and Recursion · Predict the Output · Question 11

Converting to binary with recursion Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 11 Back to Exercise

What is the output of the following Java program?

Main.java
public class Main {
    static String bin(int n) {
        if (n < 2) return String.valueOf(n);
        return bin(n / 2) + n % 2;
    }

    public static void main(String[] args) {
        System.out.println(bin(13) + " " + bin(1) + " " + bin(64) + " " + bin(0));
    }
}
  • A 1101 1 1000000 0 Correct
  • B 1011 1 0000001 0
  • C 1101 1 100000 0
  • D 13 1 64 0
Correct Answer: Option A

The higher bits come from the recursive call and the lowest bit is appended afterwards, so the digits end up in the right order.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links