1

For Java practice I started working on a method countBinary that accepts an integer n as a parameter that prints all binary numbers that have n digits in ascending order, printing each value on a separate line. Assuming n is non-negative and greater than 0, some example outputs would look like this.

I am getting pretty much nowhere with this. I am able to write a program that finds all possible letter combinations of a String and similar things, but I have been unable to make almost any progress with this specific problem using binary and integers.

Apparently the best way to go about this issue is by defining a helper method that accepts different parameters than the original method and by building up a set of characters as a String for eventual printing.

Important Note: I am NOT supposed to use for loops at all for this exercise.

Edit - Important Note: I need to have trailing 0's so that all outputs are the same length.

So far this is what I have:

public void countBinary(int n)
{
    String s = "01";
    countBinary(s, "", n);
}
private static void countBinary(String s, String chosen, int length)
{
    if (s.length() == 0)
    {
        System.out.println(chosen);
    }
    else
    {
        char c = s.charAt(0);
        s = s.substring(1);
        chosen += c;
        countBinary(s, chosen, length);
        if (chosen.length() == length)
        {
            chosen = chosen.substring(0, chosen.length() - 1);
        }
        countBinary(s, chosen, length);
        s = c + s;
    }
}

When I run my code my output looks like this.

Can anyone explain to me why my method is not running the way I expect it to, and if possible show me a solution to my issue so that I might get the correct output? Thank you!

4

1 回答 1

2

有更有效的方法可以做到这一点,但这会给你一个开始:

public class BinaryPrinter  {
  static void printAllBinary(String s, int n) {
    if (n == 0) System.out.println(s);
    else {
      printAllBinary(s + '0', n - 1);
      printAllBinary(s + '1', n - 1);
    }
  }

  public static void main(String [] args) {
    printAllBinary("", 4);
  }
}

我会让你想出更有效的方法。

于 2015-08-09T04:28:10.047 回答