Amazon Interview Question

Write code to find how many 1s are in an integer in its binary form.

Interview Answers

Anonymous

Oct 4, 2010

stackoverflow has the best answer int NumberOfSetBits(int i) { i = i - ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); return ((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; }

Anonymous

Oct 4, 2010

int count =0; while(n !=0) { count+= n&1; n>>1; }