Skip to content

UGC NET CS 2019Programming Languages and Computer Graphics › Programming in C++Verified

UGC NET CS 2019 PYQ: Consider the following C++ function f(): unsigned int f(unsigned int n) { unsigned int b=0; while (n) { b+=n…

Consider the following C++ function f():

unsigned int f(unsigned int n) {
    unsigned int b=0;
    while (n) {
        b+=n & 1;
        n>>1;
    }
return b;
}

The function f() returns the int that represents the ____P____ in the binary representation of positive integer n, where P is

  1. A
    number of 0’s
  2. B
    number of bits
  3. C
    number of consecutive 1’s
  4. D
    number of 1’s
    Correct answer

Answer

(D) number of 1’s

Approach

Trace what the loop accumulates by testing the lowest bit and shifting right.

Reviewed by UGC IQ Editorial Team.