Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computing Hamming weight, also called popcount in Java?

I am not sure how to translate this from C++ to Java. It is a function that computes the Hamming weight.

/** This is popcount_3() from:
 * http://en.wikipedia.org/wiki/Hamming_weight */
unsigned int popcnt32(uint32_t n) const
{
    n -= ((n >> 1) & 0x55555555);
    n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
    return (((n + (n >> 4))& 0xF0F0F0F)* 0x1010101) >> 24;
}

More concretely, I don't know what to use instead of uint32_t, and if I use that type whatever it is, can I just leave the rest code unchanged?

Thanks

like image 757
user1796942 Avatar asked Jan 12 '13 20:01

user1796942


1 Answers

It's implemented for you in Integer.bitCount(int i)

like image 134
zch Avatar answered Nov 17 '22 01:11

zch