ProgrammingHardTCS NQT · Infosys

What is the digit sum of 2^15 = 32768? The recursion below computes it. Assume int is 32 bits. What is printed?

What is the digit sum of 2^15 = 32768? The recursion below computes it. Assume int is 32 bits. What is printed?
#include <stdio.h>
int ds(int n) {
    return n == 0 ? 0 : n % 10 + ds(n / 10);
}
int main(void) {
    printf("%d", ds(1 << 15));
}
  1. A. 25
  2. B. 27
  3. C. 26
  4. D. 23

Correct answer: C. 26

With a 32-bit int, 1 << 15 = 32768, and ds adds n % 10 before recursing on n / 10: 8 + 6 + 7 + 2 + 3 = 26. 23 drops the leading 3, and 25 or 27 are addition slips.

More C Programming questions

Exams that ask this topic