Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program difficult to understand

Tags:

java

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));
    }
}
like image 304
user4912986 Avatar asked Jan 09 '23 08:01

user4912986


1 Answers

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"

like image 51
David W Avatar answered Jan 16 '23 14:01

David W