Different bits

Find the amount of differing bits between int a and int b.

Assumption: Both integers are positive

  1. XOR the two numbers to expose differing bits

  2. Shift and compare each element against 1 to count

public differingBits(int a, int b){
    int count = 0;
    for (int c = a ^ b; c != 0; c >> 1){
        count += (c & 1);
    }
    return count;
}

Last updated

Was this helpful?