【leetcode】461. Hamming Distance

深藏阁楼爱情的钟 2022-06-10 08:52 209阅读 0赞

一、题目描述

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
  2. Output: 2
  3. Explanation:
  4. 1 (0 0 0 1)
  5. 4 (0 1 0 0)
  6. ? ?
  7. The above arrows point to positions where the corresponding bits are different.

思路:先求出x异或y的值num,然后求出num的二进制中1的个数即是x和y的汉明距离

AC代码(c++版本)

  1. class Solution {
  2. public:
  3. int hammingDistance(int x, int y) {
  4. int num = x ^ y;
  5. int count=0;
  6. while(num){
  7. count++;
  8. num = num & (num-1);
  9. }
  10. return count;
  11. }
  12. };

go语言版本

  1. func hammingDistance(x int, y int) int {
  2. z := x^y
  3. count := 0
  4. m := 0
  5. for z!= 0{
  6. m = z%2
  7. if m == 1{
  8. count++
  9. }
  10. z = z/2
  11. }
  12. return count
  13. }

发表评论

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

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

相关阅读