how does this code works
for example
input: 5(101)
ouput: 2
the function is
scanf("%d", &a);
while(a)
{
oneina++;
a=a&(a-1);
}
printf("%d", oneina);
how does this code works
for example
input: 5(101)
ouput: 2
the function is
scanf("%d", &a);
while(a)
{
oneina++;
a=a&(a-1);
}
printf("%d", oneina);
a-1
is a
with the first 1
(from right) occurring in a
as 0
and all the bits to the right of that bit as 1
. So when you bitwise and them, you remove one 1
from a
at a time.
scanf("%d", &a); // a = 0111b (7)
while(a) // a = 0111b (7) : TRUE
oneina++; // oneina 0 --> 1
a=a & (a-1); // a = 0111b (7) & 0110b (6) = 0110b (6)
while(a) // a = 0110b (6) : TRUE
oneina++; // oneina 1 --> 2
a=a & (a-1); // a = 0110b (6) & 0101b (5) = 0100b (4)
while(a) // a = 0100b (4) : TRUE
oneina++; // oneina 2 --> 3
a=a & (a-1); // a = 0100b (4) & 0011b (3) = 0000b (0)
while(a) // a = 0000b (4) : FALSE
printf("%d", oneina); // '3'