Consider the following C++ function $f()$:
unsigned int f(unsigned int n) {
unsigned int b = 0;
while (n) {
b = b + (n bitwise AND 1);
n = n shifted right by 1;
}
return b;
}
The function $f()$ returns the integer that represents the $P$ in the binary representation of positive integer $n$, where $P$ is:
The expression $n$ bitwise AND $1$ checks the last bit of $n$.
If the last bit is $1$, then $b$ increases by $1$.
After that, $n$ is shifted right by one bit.
So, the loop checks each bit of $n$ one by one.
Therefore, $b$ counts the total number of $1$'s in the binary representation of $n$.
Online Test Series, Information About Examination,
Syllabus, Notification
and More.
Online Test Series, Information About Examination,
Syllabus, Notification
and More.