描述
如果要将整数n转换为m,需要改变多少个bit位?
说明
Both n and m are 32-bit integers.
样例
- Example 1:
Input: n = 31, m = 14
Output: 2
Explanation:
(11111) -> (01110) there are two different bits.
- Example 2:
Input: n = 1, m = 7
Output: 2
Explanation:
(001) -> (111) will change two bits.
挑战
你能想出几种方法?
解析
这里使用了二进制的各种运算
bitSwapRequired = (a, b) => {
var s = 0, c;
for (c = a ^ b; c !== 0; c = c >>> 1) {
s += c & 1;
}
return s;
}