-5
unsigned mystery(int x){               
        unsigned i = 0;
    while(x){
            x = x&(x-1);
            i++;
        }
        return i;                                     
}

I'm thinking this returns powers of '2' till the number we have given.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user1918566
  • 221
  • 1
  • 5
  • 18
  • Possible duplicate of [How to count the number of set bits in a 32-bit integer?](https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer) – Retired Ninja Jul 09 '18 at 03:22
  • This is one of my favorites; essentially the algorithm "Counting 1-bits in a sparsely populated word" in the book "Hacker's Delight" by Warren,H.S.,Jr., 2003, which cites Wegner,P.A. "A Technique for Counting Ones in a Binary Computer," Communications of the ACM 3, 5 (May 1960). – phonetagger Jul 09 '18 at 03:22
  • See also [Bit Twiddling Hacks](http://graphics.stanford.edu/~seander/bithacks.html) online. – Jonathan Leffler Jul 09 '18 at 04:18
  • I'm voting to close this question as off-topic because, while interesting if you've never seen this algorithm before, "questions" of the "puzzle solving" variety like this one will never be searched-for and therefore aren't helpful to SO. – phonetagger Jul 09 '18 at 13:15
  • This is not appropriate for Stack Overflow. If you want to see what the code does, *run it*. Don't ask us: ask the ultimate authority: the computer. – Prune Jul 09 '18 at 15:56

1 Answers1

5

It counts the number of set bits in x.

Each time through the loop, the expression x = x&(x-1) will clear the least significant set bit, and it loops until x is zero. i counts the number of iteration until that happens, so it ends up being equal to the number of set bits in the original argument.

This function is usually referred to as "popcount"

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226