It's a Java binary output recursive method, but I don't understand.

Asked 2 years ago, Updated 2 years ago, 161 views

    public static void bin(int num) {
        if(num>0) {
            int bin;
            bin = num % 2; 
            num/=2; 
            bin(num);
            System.out.print(bin);
        }
    }

    public static void main(String[] args) {
        bin(10);
    }

This is the code, but if the bin method outputs the bin method again before outputting, won't the bin where the binary result value is stored be initialized to the new value calculated again? I don't understand why you print it out after a recursive call. If you print it out first and then make a recursive call, the result value is different.

java recursive output

2022-09-22 15:41

3 Answers

It would be nice to understand recursive calls.

https://www.youtube.com/watch?v=Mga1rElzrVo

https://marobiana.tistory.com/79


2022-09-22 15:41

The recursive function is Each time you call yourself, you create a new stack space, create a local variable of the function, and use it, so it has nothing to do with the local variable value of the shear system that called you. So the calculation result of the shear will not be initialized. And what you print out after a recursive call is the same formula for binary numbers


2022-09-22 15:41

The pseudocode is the same as the Java code above. Think for yourself about which line corresponds to which.


Output to binary (number of outputs): // If the number of outputs was 101001
   Last digit = Get last digit (can output) // Last digit is 1
   Last digit minus = last digit minus (outputable) // last digit minus 10100
   Output to binary (minus the last digit) // where the top five digits are 10100.
   Last digit output (last digit) // last digit output 1 output.
                                           // Eventually, 101001 is output.


2022-09-22 15:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.