繁体   English   中英

解释递归代码的逐步执行以在Java中将Decimal转换为Binary

[英]Explain the Step by step execution of the recursion code to convert Decimal to Binary in Java

因此,这是在Java中使用递归将十进制数转换为二进制数的代码,该代码可以正常工作。 但是我很困惑编译器如何执行此代码,就像我用纸来解决它一样,但是我无法理解编译器如何使用它并生成输出。 当我在纸上解决该问题时,该解决方案对我没有任何意义。 如果有人能告诉我它是如何工作的,请。 现在已经坐了1个多小时了。

如果有人描述我逐步执行代码并获得与代码相同的输出,我将很高兴。

使用了如下所示的递归。

public class RecursionPractice {

    public static void main(String[] args) {
    System.out.println("The converted number is " + dectoBin(7));
    }

private static int dectoBin(int n){
        if(n == 0 )
            return 0;
        else
            return  n % 2 + 10 * dectoBin(n/2);
    }
}

输出符合预期

转换后的数字为111

流程结束,退出代码为0

逐步执行如下。 希望你现在能理解。

1st call: dectoBin(7) =>  return  7 % 2 + 10 * dectoBin(7/2); => 1 + 10 * dectoBin(3);

2nd call: dectoBin(3) =>  return  3 % 2 + 10 * dectoBin(3/2); => 1 + 10 * dectoBin(1);

3rd call: dectoBin(1) =>  return  1 % 2 + 10 * dectoBin(1/2); => 1 + 10 * dectoBin(0);

4th call: dectoBin(0) =>  return  0; // base case 

评估所有这些

 dectoBin(7);
 7 % 2 + 10 * dectoBin(3);
 7 % 2 + 10 * ( 3 % 2 + 10 * dectoBin(1) );
 7 % 2 + 10 * ( 3 % 2 + 10 * ( 1 % 2 + 10 * dectoBin(0) ) );

dectoBin(0)返回0因此,

  7 % 2 + 10 * ( 3 % 2 + 10 * ( 1 % 2 + 10 * 0 ) );
  7 % 2 + 10 * ( 3 % 2 + 10 * ( 1 ) );
  7 % 2 + 10 * ( 11 );
  7 % 2 + 110;
  1 + 110;
  111;

第一次迭代:7%2 + 10 * __

第二次迭代3%2 + 10 * __

第3次迭代1%2 + 10 * __

第4次迭代返回0

第3次迭代1%2 + 10 * 0 = 1

第二次迭代3%2 + 10 * 1 = 1 + 10 = 11

第一次迭代:7%2 + 10 * 11 = 1 + 110 = 111

递归是循环的一种,如果您在代码中要解决的问题(可能是将列表转换为特殊格式的字符串),但是该问题中包含更多相同问题的实例(该列表中包含更多列表)它需要以相同的方式进行格式化)。

在您的示例中,当decToBin()方法的参数设置为0时,循环将停止。 循环基本上继续进行,并不断将数字除以2,直到达到0或更小然后停止。

7传递给方法:

  1. 7%2 + 10 * dectoBin(7/2) = 1 + 10 * dectoBin(3) 现在n是3。
  2. dectoBin(3) ):3%2 + 10 * dectoBin(3/2) = 1 + 10 * dectoBin(1) 现在n是1
  3. dectoBin(1) ):1%2 + 10 * dectoBin(1/2) = 1+ 10 * dectoBin(0) 现在n为0
  4. dectoBin(0) ):返回0;

向后退: 1 + 10* (1 +10 *(1+10*0))=1+ 10*(1 + 10)= 1 +110 =111

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM