Pergunta de entrevista da empresa Marvell Technology

count the 1s in an integer

Respostas da entrevista

Sigiloso

24 de out. de 2014

int main() { int c, i=10; while(i) { i=i&(i-1); c++; } printf("no, of ones in number 10 is %d\n", c); }

Sigiloso

15 de fev. de 2019

while(i) { if(i & 1) count++; i >>= 1; } cout << i << endl;

Sigiloso

10 de jan. de 2020

So the best solution for this problem is to perform the bitwise and operation between number and number-1, every time you do this will take off the right most set bit. number of time this loops goes will give the number of bits set in the number ex: int count_set_bits(int number) { int count=0; while(number) { count++; number = number & (number - 1); } return count; }

Sigiloso

24 de out. de 2014

int main() { int c, i=10; while(i) { } }