简体   繁体   中英

Program difficult to understand

I have a program and I don't understand its result. It gives me 110 , but I don't know how it's even possible. I call it only once. For me, it should be 3?? Thank you

public class Test {
    public static String operator (int n) {
        return((n == 0) ? "" : operator(n / 2) + (n % 2));
    }

    public static void main(String[] args) {
        System.out.println(operator(6));
    }
}

The recursion in this function causes the middle to be repeatedly evaluated with the modulus of the original argument appended with each iteration. So follow the expansion of operator(6)

  1. operator(6) => operator(6/2)+(6%2) = operator(3) + "0"
  2. operator(3) => operator(3/2)+(3%2) = operator(1) + "1"
  3. operator(1) => operator(1/2) + (1%2) = operator(0) + "1"
  4. operator(0) = > ""

The recursion ends at the 4th iteration, and the unwound result becomes "110"

It's a simple recursive method, which can be expressed like this to make it more readable:

operator(0) = ""
operator(n) = operator(n / 2) + (n % 2)

So following those rules, operator(6) = "110" as follows:

operator(6) = operator(6 / 2) + (6 % 2)
            = operator(3) + 0
            = operator(3 / 2) + (3 % 2) + 0
            = operator(1) + 1 + 0
            = operator(1 / 2) + (1 % 2) + 1 + 0
            = operator(0) + 1 + 1 + 0
            = "" + 1 + 1 + 0
            = "110"

operator returns a string. So the result of operator(n/2)+(n%2) is adding (concatenating) the string from operator(n/2) with the value of (n%2) which is automatically converted to a string so that it can be concatenated.

Try changing operator to return int and changing the line to read:

return((n == 0) ? 0 : operator(n/2)+(n%2));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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