0

Doing a question on codility and was Asked to take two numbers and get the product. Then get the binary repesentation of that number and count the number of one's that are in the binary number. My code is

    return method(int a, int b)
    {
    int count=0;
    int num;
    num = a* b;
    while(num>0)
    {
       if(num %2 ==1)
       {
           count++;
       }
     num = num >> 1;
    }
  return count;
  }

Yet it only gives 50% correctness. Can anyone explain this. Is there something i missed that i should be aware off.

1 Answers1

1

Using the modulo operator won't correctly count the bits in a negative number. Use "num & 1" instead. Also, make sure you're using unsigned right shifts or a negative number may produce an infinite loop.

And as Lashane said, use a 64 bit product if possible.

Paul Kienitz
  • 878
  • 6
  • 25