对于Java实践,我开始研究一个方法countBinary
,它接受整数n
作为参数,以升序打印所有具有n
位数的二进制数,将每个值打印在单独的行上。假设n非负且大于0,一些示例输出将如下所示:
我什么也没得到。我能够编写一个程序来查找String
和类似的东西的所有可能的字母组合,但是我无法在使用二进制和整数的这个特定问题上取得几乎任何进展。
显然,解决这个问题的最好方法是定义一个接受不同于原始方法的参数的辅助方法,并通过构建一组字符作为最终打印的字符串。
重要注意:在这个练习中,我不应该使用for循环。
编辑-重要注意:我需要有尾部0,以便所有输出长度相同。
到目前为止,这是我所拥有的:
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;
}
}
当我运行我的代码时,我的输出看起来像这样:
谁能向我解释为什么我的方法没有按照我期望的方式运行,如果可能的话,向我展示解决我的问题的方法,以便我可以得到正确的输出?谢谢你!
有更有效的方法,但这将给你一个开始:
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);
}
}
我让你找出更有效的方法。