Bloomberg LP Interview Question
Software Engineer / DevelopersXiao, not entirely correct, you are giving a solution to the number of 1's in the binary representation. but most likely the interviewer would have asked the number of bits high, when a byte is stored in memory where the number is stored in 2s complement. so only shifting would give the correct answer, most likely the left shift, as right shift would have problems with negative numbers.
Nithesh is correct. But right shift always has problem with signed numbers. If it is an negative number, then right shift gets 1's coming from left rather than 0's. Thus, it would be better to use left shift of 1 as the bit mask instead.
@Kyra: Good point about the number being negative. So, one can always typecast the received number to an unsigned type before applying Nithesh's algorithm. That would be way easier than doing a left shift.
One other way would be to have look-up. Since 1 byte corresponds to 255 numbers, having a 255 entry table and then doing a table-lookup would be very fast.
#include<iostream>
using namespace std;
int main()
{
int num = 13;
int count = 0;
while(num!=0)
{
if((num & 256) == 256)
{
count++;
num = num << 1;
}
else
num = num << 1;
}
cout << count;
}
nitish's answer is missing the else. but i am still not entirely sure whether this answer is correct or not :|
n = (n & 0x55555555) + ((n & 0xaaaaaaaa) >> 1); //Only this line if 2 bits can represent the integer
n = (n & 0x33333333) + ((n & 0xcccccccc) >> 2); //This and all above if 4 (or less) bits can represent the integer
n = (n & 0x0f0f0f0f) + ((n & 0xf0f0f0f0) >> 4); //This and all above if 8 (or less) bits can represent the integer
n = (n & 0x00ff00ff) + ((n & 0xff00ff00) >> 8); //This and all above if 16 (or less) bits can represent the integer
n = (n & 0x0000ffff) + ((n & 0xffff0000) >> 16); //This and all above if 32 (or less) bits can represent the integer
So all above four lines can be used for any 32 bit integer.
One of the best implementations of the above algorithm is that if we do a & operator with the digit 1 and then if the result comes to be 1 which means that the variable temp contains a bit which is 1 and then, we can increment the counter variable and then we can shift the number to right side and then again check till the number is not equal to zero.
Implementation:
#include<bits/stdc++.h>
using namespace std;
int findbits(int num){
int count = 0;
int temp = num;
while(temp != 0){
if((temp & 1) == 1){
count++;
temp = temp>>1;
}
}
return count;
}
int main(){
cout<<findbits(3)<<endl;
}
Count = 0;
- Nithesh January 13, 2010temp = num;
while(temp != 0)
{
if((temp & 1) == 1)
{
count++;
temp = temp>>1;
}
}