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

编程入门 行业动态 更新时间:2024-10-25 12:28:58
本文介绍了如何在递归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.

推荐答案

调试器是一个很好的理解工具外部代码。如果输出是格雷码,那么这就是代码正在做的事情。学习格雷码。 格雷码 - 维基百科 [ ^ ] 你应该学会使用调试器尽快。而不是猜测你的代码在做什么,现在是时候看到你的代码正在执行并确保它完成你所期望的。 注意比列出格雷码并不比按顺序列出二进制数复杂,它只需要添加一小步。递归是没有必要的。 ----- 调试器允许你逐行跟踪执行,检查变量,你会看到有一个点它停止做你期望的事。 调试器 - 维基百科,免费的百科全书 [ ^ ] docs.oracle/javase/7/docs/technotes/tools/windows/jdb.html [ ^ ] www.jetbrains / idea / help / debugging-your-first-java-application.html [ ^ ] 调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做什么进行比较。 调试器中没有魔法,它没有找到错误,它只是帮助你。当代码没有达到预期的效果时,你就会接近一个错误。 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[^] docs.oracle/javase/7/docs/technotes/tools/windows/jdb.html[^] www.jetbrains/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.

更多推荐

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

本文发布于:2023-11-22 20:13:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618848.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   灰色   代码   如何在   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!