河内塔柜台

编程入门 行业动态 更新时间:2024-10-22 23:46:56
本文介绍了河内塔柜台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经为《河内的塔》游戏编写了代码.我不知道该程序执行了多少次后如何实现该计数器.任何帮助将不胜感激.

I have written a code for Towers Of Hanoi game. I don't know how to implement a counter for this program on how many times it ran. Any help will be much appreciated.

public class MainClass { public static void main(String[] args) { int nDisks = 3; doTowers(nDisks, 'A', 'B', 'C'); } public static void doTowers(int topN, char from, char inter, char to) { if (topN == 1){ System.out.println("Disk 1 from " + from + " to " + to); }else { doTowers(topN - 1, from, to, inter); System.out.println("Disk " + topN + " from " + from + " to " + to); doTowers(topN - 1, inter, from, to); } } }

推荐答案

将doTowers的返回类型从void更改为int,并将返回值设置为:

Change the return type of doTowers from void to int, and set the return value to:

  • 如果topN == 1,则返回1;
  • 否则返回两个doTowers()加1的总和.
  • if topN == 1, return 1;
  • else return the sum of two doTowers() plus 1.
  • 逻辑类似于问题的算法.玩弄找出来吧!

    The logic is similar to the algorithm of the problem. Have fun figuring it out!

    您还可以使用静态全局变量,但这可以说是不好的编程风格.

    You could also use a static global variable, but that's arguably bad programming style.

    更多推荐

    河内塔柜台

    本文发布于:2023-11-30 03:12:26,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1648533.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:河内   柜台

    发布评论

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

    >www.elefans.com

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