Write a method that counts the number of enabled bits in an Integer.
Interview Answers
Anonymous
Oct 26, 2014
The bits question was a particularly hard for me because I had never done bit manipulation before.
Anonymous
Nov 14, 2014
Bit manipulation can be tricky because it isn't done that often. Here is a pretty simple function that should work as a solution to this problem:
public static int chkEnabledBits(int chkInt)
{
int numEnabledBits = 0;
while(chkInt > 0)
{
numEnabledBits += chkInt&1;
chkInt = chkInt >> 1;
}
return numEnabledBits;
}
Anonymous
Nov 17, 2014
The previous answer forgot about negative numbers! :( Java represents integers in two's compliment. Here's a simple albeit hacky solution:
public static int chkEnabledBits(int chkInt)
{
int numEnabledBits = 0;
int numChkedBits = 0;
while( (chkInt != 0) && (numChkedBits > 1;
numChkedBits++;
}
return numEnabledBits;
}