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.
-
Code Analysis:
int func(int num) { int count = 0; while (num) { count++; num >>= 1; } return (count); }In each iteration,
countincreases by 1 andnumis right-shifted by 1 bit (num >>= 1), discarding its least significant bit. The loop terminates whennumbecomes 0.
Hence, the function computes the position of the most significant 1-bit, which is (the total number of bits in the binary representation ofnum). -
Evaluate for :
- Find powers of 2 enclosing 435:
- In binary:
- The binary string has exactly bits.
- After 9 right-shift operations,
numbecomes 0.
- Find powers of 2 enclosing 435:
-
Therefore,
func(435)returns 9.
9
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.