题目
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
题解
我使用了每次右移,统计奇偶性的解法——
import java.util.*; import java.io.*; class BitCounting { public static int countBits(int n){ int result = 0; while (n!=0) { if ((n&1) == 1) result ++; n >>= 1; } return result; } }
标准解法中,我比较喜欢的有如下代码——
直接使用Integer的库函数
public class BitCounting { public static int countBits(int n){ return Integer.bitCount(n); } }
转换为字符串处理,其中用到了Java中的Lambda表达式
public class BitCounting { public static int countBits(int n){ return (int) Integer.toBinaryString(n).chars() .filter(c -> c == '1') .count(); } }