Ferozeh dot Com
Expert advice on tech interviews !
about ferozeh

Ferozeh

Similar Questions


permutations of a string


delete a word in a string


reverse a string


detect a palindrome


convert integer to string

Question

Difficulty Level: 2

  • How can you count the number of 1s in a given byte?

Solution

Explanation Quality:2.5

This question refers to bit manipulation. We need to know the AND operator before solving this question. And and operation gives the following results

Operand 1
Operand 2
Operan1 AND Operand2
0
0
0
1
0
0
0
1
0
1
1
1

Now we will create a mask, a mask is just another byte we will use to detect ones in a given byte. So the scheme is as follows:

given byte 00101101
mask 00000001
&
00000001

Note that when we AND the bytes each of the corresponding bits are ANDED togather. Since the last bits of the above bytes both are 1 that is why as a resultant we get 1. If the last bit of the given byte was zero then on ANDing with the mask the result would be 0. So whenever our result is 1 we have essentially detected a 1 in the given byte. Each time we AND the two bytes we right shift the given byte by one place in order to test the next bit. We could very well left shift the mask by one.


char mask = 1; //assuming char is 1 byte
char givenByte = 45;
int count = 0;

for(i = 0; i < 8; i++){

 if( (GivenByte & fast) == 1){

  count++ //Another 1 detected
 }
mask << 1; //left shift the mask by 1
}

cout<<count; //number of 1s equal the count variable

Note that this is the simplest solution that can be thought of and is expected of you for an entry level position. However a better and faster solution exists which I don't discuss here since it can only be expected if you've been playing with bits for a long time.




Previous Next