Recursion

AP Computer Science A· difficulty 4/5

Consider:

<code class="language-java">public static int g(int n, int acc) { if (n == 0) return acc; return g(n / 2, acc + n % 2); } </code></pre> What does <code>g(13, 0)</code> return?

  • A

    3

    check_circle
  • B

    0

  • C

    13

  • D

    4

Explanation

The function counts the number of 1-bits in n. 13 = 1101 in binary, which has three 1-bits. Trace: g(13,0) -> g(6,1) -> g(3,1) -> g(1,2) -> g(0,3) -> 3.

Want 10 more like this — adaptive to your weak spots?

Related questions