The Gateway to Computer Science Excellence
+1 vote
208 views

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. number of $0$’s
  2. number of bits
  3. number of consecutive $1$’s
  4. number of $1$’s
in Object Oriented Programming by Veteran (431k points)
edited by | 208 views

1 Answer

+1 vote
Ans $4)$

Program counting number of $1.$

It is given in question, that $n$ represent, binary representation for $n.$

Now, if we check 'while' loop, $b$ is increments it's value only  when last digit of $n$ is $1.$ and then it is right sifting the value.

So, $b$ is returning nothing but number of $1's$ in $n.$
by Veteran (119k points)

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,737 questions
57,365 answers
198,493 comments
105,260 users