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)
The recursion ends at the 4th iteration, and the unwound result becomes "110"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With