TripAdvisor Interview Question: After asking the details of m... |

Interview Question

Senior Software Engineer Interview Toronto, ON

After asking the details of my current role, he only gave

  me a simple coding question. Write a function using C++ or Java that is passed an integer and it returns the number of bits set to 1. Is there a way to improve your solution and make it faster and more efficient?
java, c++, algorithm, developer

Interview Answer

3 Answers


There are obviously multiple solutions:

Solution 1:
Set sum = 0
Find the remainder by dividing by 2.
Divide by 2 for the next iteration.

Solution 2--much better.
Set sum = 0
Start loop
Set mask = 1
sum += mask & number
return sum

Interview Candidate on 2013-12-02

There is another way, that is explained here: (with just 24 operation and without any cycle you can find the number of bit set to 1)

Ivan on 2013-12-11

An example in Java with 10000 results in answer 5

int number = 10000;
        int numberOfBitsSet = 0;

        for (int i = 1; i <= number;) {
            int result = (i & number);
            if (result != 0) {
            i = i << 1;


Prakash on 2014-04-30

Add Answers or Comments

To comment on this, Sign In or Sign Up.