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

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?
Tags:
java, c++, algorithm, developer
Answer

Interview Answer

3 Answers

0

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
Loop
return sum

Interview Candidate on 2013-12-02
2

There is another way, that is explained here: http://en.wikipedia.org/wiki/Hamming_weigh (with just 24 operation and without any cycle you can find the number of bit set to 1)

Ivan on 2013-12-11
0

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) {
                numberOfBitsSet++;
            }
            i = i << 1;
        }

        System.out.println(numberOfBitsSet);

Prakash on 2014-04-30

Add Answers or Comments

To comment on this, Sign In or Sign Up.