描述
如果要將整數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;
}
運行結果


轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/128205.html
標籤:其他
