Apple Interview Question

Write a program to count the '1' bits of an integer.

Interview Answer

Anonymous

Mar 23, 2010

int sumbits(uint32_t x) { int i,cnt; for (i=32,cnt=0;i>0;) { cnt+=(x>>(--i) & 0x1); } return cnt; } /* not sure if this is exact answer i wrote down there is other tricky solutions using x&(x-1) for those adept at bit hackery */