Domanda di colloquio di Garmin

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

Risposte di colloquio

Anonimo

20 feb 2013

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

5

Anonimo

18 gen 2013

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

1