OOPS
August 29, 2024OOPS
August 29, 2024OOPS
|
Question 149
|
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
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
|
number of 0’s
|
|
|
number of bits
|
|
|
number of consecutive 1’s
|
|
|
number of 1’s
|
Question 149 Explanation:
& operator does the binary and operation of both value and 1
when b += n & 1 is given
n and 1, both will be converted to binary and binary & operation is calculated
any number & 000000001
it will only compare the last bit of both numbers, if both right most bit is 1 then the value is incremented by 1 and the number n is right shifted that means it loses the value of right most bit and again new right most bit is binary anded with 1.
So the value is nothing but the number of 1’s of the binary format of number.
when b += n & 1 is given
n and 1, both will be converted to binary and binary & operation is calculated
any number & 000000001
it will only compare the last bit of both numbers, if both right most bit is 1 then the value is incremented by 1 and the number n is right shifted that means it loses the value of right most bit and again new right most bit is binary anded with 1.
So the value is nothing but the number of 1’s of the binary format of number.
Correct Answer: D
Question 149 Explanation:
& operator does the binary and operation of both value and 1
when b += n & 1 is given
n and 1, both will be converted to binary and binary & operation is calculated
any number & 000000001
it will only compare the last bit of both numbers, if both right most bit is 1 then the value is incremented by 1 and the number n is right shifted that means it loses the value of right most bit and again new right most bit is binary anded with 1.
So the value is nothing but the number of 1’s of the binary format of number.
when b += n & 1 is given
n and 1, both will be converted to binary and binary & operation is calculated
any number & 000000001
it will only compare the last bit of both numbers, if both right most bit is 1 then the value is incremented by 1 and the number n is right shifted that means it loses the value of right most bit and again new right most bit is binary anded with 1.
So the value is nothing but the number of 1’s of the binary format of number.
