Consider the function func shown below: int func(int num) { int count = 0;…
2014
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 __________.
Attempted by 320 students.
Show answer & explanation
Correct answer: 9
Answer: 9
Explanation: The loop repeatedly shifts the number right until it becomes zero. Each right shift removes one binary digit, so the count equals the number of bits in the binary representation of the positive integer.
Binary representation: 435 in binary is 110110011.
Number of bits: that representation has 9 bits, so the loop runs 9 times.
Alternative formula: floor(log2(435)) + 1 = 8 + 1 = 9.
Conclusion: The function returns 9 for func(435).