Pergunta de entrevista da empresa Arm

How would you count the number of set bits in an integer?

Resposta da entrevista

Sigiloso

19 de abr. de 2019

Lazy answer It depends on the size on the size of integer Lets suppose 16 bits integer create an array with 65536 positions populate as follow Position Number ofset bits [0] = 0 [1] = 1 [2] = 1 [3] = 2 .... [FF] = 16 To get the number of set bits of a int, just use the int as the index of the array lets say number is 65 number of set bits = [65] I told you, Lazy Answer Not so lazy answer. Use assembly. Assume int is 16 bits 1) start W = 0 2) start R = 0 3) start N = Number 4) shift right N and collect the shifted bit in c bit 5) if c=1 -> add W,1 6) add R,1 7) if R<16 jump to 4) 8) Answer is in W