Java Recursion. Output for the following program

回眸只為那壹抹淺笑 提交于 2019-12-24 09:37:35

问题


I am looking for some brief explanations on how the below program or code works.Thanks

public void Convert( int iNum )
{
    int m = 0;
    if (iNum == 1 )
        System.out.print( iNum );
    else
    {
        m = iNum % 2;
        Convert(iNum/2);
        System.out.print(m);
    }
}

回答1:


This program tries to convert a decimal number to binary using recursion. Lets take an example:

Decimal 5 -> Binary 101

Convert(5):
m = 5 %2 -> 1
   Convert(2):
       m -> 2%2 -> 0
       Convert(1)
          The first if is true: -> 1

Output: 101 



回答2:


It is a simple recursive call The if part will get executed only once ie, when inum=1; The else part keeps only calling convert (each time cutting the value of inum by 2) and when we cannot further dive inum first the if part gets executed and the step back to the next stacked recursive version and prints the remainder we get on dividing inum/2.



来源:https://stackoverflow.com/questions/8583789/java-recursion-output-for-the-following-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!