LeetCode算法笔记-Day68
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.
1 2 3 4 5 6 7 8 9 10 11 12 13
| 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.
|
方法一
Answer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
var hammingDistance = function(x, y) { let res = 0, x_bits = x.toString(2).split(""), y_bits = y.toString(2).split(""), x_p = x_bits.length - 1, y_p = y_bits.length - 1; while(x_p >= 0 || y_p >= 0){ let x_bit = typeof(x_bits[x_p]) !== 'undefined' ? x_bits[x_p] : 0, y_bit = typeof(y_bits[y_p]) !== 'undefined' ? y_bits[y_p] : 0; if(x_bit != y_bit) res += 1; x_p -= 1; y_p -= 1; } return res; };
|
方法二:异或
Answer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
var hammingDistance = function(x, y) { let res = 0, xor = (x^y).toString(2).split("");
for(let i=0;i<xor.length;i++){ if(xor[i] == 1) res += 1; }
return res; };
|