Interview Question

Software Engineer Interview Olathe, KS

Given an integer, write a function that returns the number

  of bits in the integer that are set.
Answer

Interview Answer

2 Answers

1

int countSet(int x) {
    int count = 0;

    while(x != 0) {
         x = x ^ (x-1);
         count++;
    }
    return count;
}

Interview Candidate on Jan 18, 2013
4

int countSet(int x) {
    int count = 0;

    while(x)
    {
        if(x & 0x0001) count++;
        x = x >> 1;
    }

    return count;
}

Anonymous on Feb 20, 2013

Add Answers or Comments

To comment on this Question, Sign In with Facebook or Sign Up