Program is hard to understand

I have a program, and I do not understand its result. It gives me 110, but I do not know how this is possible. I call it only once. For me it should be 3 ?? Thanks 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));
    }
}
+4
source share
3 answers

The recursion in this function forces the middle to be repeatedly evaluated with the module of the original argument applied to each iteration. So, we follow the extension of the operator (6)

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

4- , "110"

+6

, , :

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

, , operator(6) = "110" :

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"
+3

operator . , operator(n/2)+(n%2) () operator(n/2) (n%2), , .

operator, int, :

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

All Articles