Java Recursion. Output for the following program

2019-08-08 03:39发布

问题:

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.