-1

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);
eightnoteight
  • 234
  • 2
  • 11

2 Answers2

1

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.

HelloWorld123456789
  • 5,299
  • 3
  • 23
  • 33
0
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'
Mahonri Moriancumer
  • 5,993
  • 2
  • 18
  • 28