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
     
  • 相关阅读:
    发送电子邮件
    PHP Session
    Cookie
    Python基础语法
    Python中文编码
    Python简介
    PHP文件上传
    基于1.22.1版本的k8s部署
    k8s基于NFS创建动态存储StorageClass
    关于在k8s-v1.20以上版本使用nfs作为storageclass出现selfLink was empty, can‘t make reference
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/6903008.html
Copyright © 2011-2022 走看看