Write a function that takes an (unsigned) integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
Good Solution1:
public class BitCounting {
public static int countBits(int n){
return Integer.bitCount(n);
}
}
Good Solution2:
public class BitCounting {
public static int countBits(int n){
int ret = n % 2;
while ((n /= 2) > 0) ret += n % 2;
return ret;
}
}
Good Solution3:
public class BitCounting {
public static int countBits(int n){
return (int) Integer.toBinaryString(n).chars()
.filter(c -> c == '1')
.count();
}
}