461. Hamming Distance leet-code

冷不防 2022-07-11 15:19 199阅读 0赞

461. Hamming Distance leet-code

题目介绍

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.

  1. Example:
  2. Input: x = 1, y = 4
  3. Output: 2
  4. Explanation:
  5. 1 (0 0 0 1)
  6. 4 (0 1 0 0)
  7. The above arrows point to positions where the corresponding bits are different.

思路

1.两个数求异或
2.计算其1的个数

  1. func hammingDistance(x int, y int) int {
  2. temp := x^y
  3. cnt := 0
  4. for ; temp != 0; {
  5. temp = temp&(temp-1)
  6. cnt++
  7. }
  8. return cnt
  9. }

发表评论

表情:
评论列表 (有 0 条评论,199人围观)

还没有评论,来说两句吧...

相关阅读