Google Interview Question
1,220 Interview Reviews |
Back to all Google Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Software Engineer In Test at Google:
Design a function which returns the number of set bits in a given number, when expressed in binary
See more for this Google Software Engineer In Test Interview
Helpful Question?
Yes |
No
Inappropriate?
Answers & Comments (3)
0 of 1 people found this helpful
/* return n of set bits in a signed int */
int numBits(int num) {
int numBits = 0;
while (num != 0) {
if (num < 0) ++numBits;
num <<= 1;
}
return numBits ;
}
Helpful Answer?
Yes |
No
Inappropriate?
/* lookup table with number of bits set per byte */
const short lookupTable[256] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, ... };
int numBits(int num)
{
unsigned char *p = (unsigned char *)# // not necessarily required, but makes for easier reading
return lookupTable[p[0]] + lookupTable[p[1]] + lookupTable[p[2]] + lookupTable[p[3]]; // assumes 32 bit integer
}
Helpful Answer?
Yes |
No
Inappropriate?
To comment on this
question,
Sign In with Facebook or
Sign Up
2 of 3 people found this helpful
by Xin Li:
{
int numBits = 0;
while(num > 0)
{
if(num % 2) numBits++;
num /= 2;
}
return numBits;
}