461. Hamming Distance 漢明距離
❀ Origin
Problem
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x
and y
, calculate the Hamming distance.
Note
- 0 ≤ x, y < 231.
Example
1 | Input: x = 1, y = 4 |
❀ 翻譯
問題
兩個數的漢明距離是相對應的 bits 位置有所不同的數量.
給定兩個數 x
和 y
, 計算出漢明距離.
注意
- 0 ≤ x, y < 231.
❀ Solution
Idea
- 用 互斥或閘(XOR) 算出兩數的差異數的十進位值
- 用 while(){} 算出該數的二進位制有幾個 1
JavaScript
1 | /** |
Execution
1 | 5 ^ 10 = 15 |