Google Interview Question: Count the number of bits set ... | Glassdoor.co.uk

Interview Question

Software Engineering Intern Interview London, England

Count the number of bits set in an integer. What is your

  favorite language and what you don't like about that language.
Answer

Interview Answer

3 Answers

0

This question totally caught me off guard because I haven't dealt anything about bit manipulation before

Interview Candidate on 31 Mar 2014
0

>Count the number of bits set in an integer
I assume that this questrion suppose to count 1's (1 = bit is set(or enabled))
1 - enter an integer (for example 2)
2 - put binary form of 2 into a string and count 1's
(in C++ you can use a bitset and it's method called count:
...
bitset x(number);
cout << x.count(); //count number of 1's (bits which set)
...

Andrey on 6 Jun 2014
3

The interviewer probably wanted you to use bit-wise operations. In java you would bit-wise "and" the number with
1 left-shifted by a number i from 0 to 31. This would return zero if the i-th bit is not set, or something other than zero otherwise.

public int getBits(int n)
 {
    int count=0;
    for(int i=0;i<31;i++)//bit which we are checking
      {
        if(n & (1<

Lenny on 10 Sep 2014

Add Answers or Comments

To comment on this, Sign In or Sign Up.