Question

Consider the function func shown below:

int func(int num) {
    int count = 0;
    while (num) {
        count++;
        num >>= 1;
    }
    return (count);
}

The value returned by func(435) is _____.

Official answer and solution
Official answer
9
From
Official GATE 2014 answer key

Solution

Trace the loop to observe that it computes the bit-length of the binary representation of the input integer.

  1. Code Analysis:

    int func(int num) {
        int count = 0;
        while (num) {
            count++;
            num >>= 1;
        }
        return (count);
    }
    

    In each iteration, count increases by 1 and num is right-shifted by 1 bit (num >>= 1), discarding its least significant bit. The loop terminates when num becomes 0.
    Hence, the function computes the position of the most significant 1-bit, which is ⌊log⁡2(num)⌋+1\lfloor \log_2(\text{num}) \rfloor + 1 (the total number of bits in the binary representation of num).

  2. Evaluate for num=435num = 435:

    • Find powers of 2 enclosing 435:
      28=256≤435<512=29.2^8 = 256 \le 435 < 512 = 2^9.
    • In binary:
      435=256+128+32+16+2+1=1101100112.435 = 256 + 128 + 32 + 16 + 2 + 1 = 110110011_2.
    • The binary string 1101100112110110011_2 has exactly 99 bits.
    • After 9 right-shift operations, num becomes 0.
  3. Therefore, func(435) returns 9.

Final answer

9

Common trap

Counting only the number of set bits (popcount = 6) instead of the total number of bits shifted until zero.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2014 Computer Science and Information Technology (CS) Session 2
Question
20 of 65, printed as CS Q.10
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.