zoukankan      html  css  js  c++  java
  • LeetCode 461. Hamming Distance(easy难度c++)

    一、汉明距离

    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.

    解释:题目难度不大,求汉明距离,也就是把数字转成二进制之后按位异或运算,求最后得到的数字中1的数量即可
    反思:我最开始做这道题时,直接return(X^Y),最后结果显然不对,应当返回x^y最后得到二进制数字中1的数量。我的思路是先把两个数进行异或运算,之后按照除2取余得到最后一位的数字,如果为1,计数变量加一,如果为0,右移一位,循环进行,直到最后数字为0,操作结束。
    代码如下:
    class Solution {
    public:
        int hammingDistance(int x, int y) {
           int z=x^y,count=0;
           while(z!=0)
           {
               if(z%2==1)
                  count++;
               z = z>>1;
           }
         return count;
        }
    };
    View Code
     
  • 相关阅读:
    OpenACC 书上的范例代码(Jacobi 迭代),part 4
    WRF 安装备忘
    荒川网格
    位运算骚操作 Part 3
    CUDA compiler driver nvcc 散点 part 2
    稀疏矩阵 part 5
    稀疏矩阵 part 4
    稀疏矩阵 part 3
    稀疏矩阵 part 2
    稀疏矩阵 part 1
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/6903008.html
Copyright © 2011-2022 走看看