Garmin interview question

Given an integer, write a function that returns the number of bits in the integer that are set.

Interview Answers

Anonymous

20 Feb 2013

int countSet(int x) { int count = 0; while(x) { if(x & 0x0001) count++; x = x >> 1; } return count; }

5

Anonymous

18 Jan 2013

int countSet(int x) { int count = 0; while(x != 0) { x = x ^ (x-1); count++; } return count; }

1