Garmin Interview Question

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

Interview Answers

Anonymous

Feb 20, 2013

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

5

Anonymous

Jan 18, 2013

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

1