Markdown

461. Hamming Distance

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 ≤ xy < 231.
Example:
Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

The above arrows point to positions where the corresponding bits are different.


/**
 * @param {number} x
 * @param {number} y
 * @return {number}
 */
var hammingDistance = function(x, y) {
    return(Number((x^y).toString(2).split("").reduce((a,b)=>Number(a)+Number(b))));
};


思路:
1. 先確定x,y >0 屬於unsigned numbers 這是題目給的,
這樣就不用做處理可以直接做XOR
2. XOR完了之後會將結果輸出為十進位整數,接著使用toString轉二進位再塞進陣列
3. 將陣列累加 看有幾個一 由於此時陣列元素還是string因此先轉num在進行累加
輸出結果會變成string再轉回num 得到結果



觀摩區:

直接把0砍掉然後算字串多長wow

D
 
we need only one line
/**
 * @param {number} x
 * @param {number} y
 * @return {number}
 */
var hammingDistance = function(x, y) {
 return new Number(x ^ y).toString(2).replace(/0/g, '').length;
};

留言