灰色模型java编写,如何在递归java中编写灰色代码

public class GrayCode {

//append reverse of order n gray code to prefix string, and print

public static void yarg(String prefix, int n) {

if (n == 0) StdOut.println(prefix);

else {

gray(prefix + "1", n - 1);

yarg(prefix + "0", n - 1);

}

}

//append order n gray code to end of prefix string, and print

public static void gray(String prefix, int n) {

if (n == 0) StdOut.println(prefix);

else {

gray(prefix + "0", n - 1);

yarg(prefix + "1", n - 1);

}

}

public static void main(String[] args) {

int n = Integer.parseInt(args[0]);

gray("", n);

}

}

Could someone explain how this code works?

What I have tried:

I've been trying to write method for gray code and my way was very unneficient, many loops and lists. It's a lot better to use recursion and I found this example but I am not realy sure if I know how it works.

解决方案

The debugger is a great tool to comprehend foreign code.If the output is gray code, then that is what the code is doing. Study Gray code.

Gray code - Wikipedia[^]

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

Note than listing Gray code is no more complicated than listing binary number in order, it just need to add a small step. recursion is not necessary.

-----

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.

Debugger - Wikipedia, the free encyclopedia[^]

http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]

https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.

There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值