zoukankan      html  css  js  c++  java
  • 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.

    Note:
    0 ≤ xy < 2^31.

    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;
    原始代码如下:
     1 class Solution {
     2 public:
     3     int hammingDistance(int x, int y) {
     4         int dis = 0;
     5         while(x && y){
     6             dis += (x & 1) ^ (y & 1);//x&1异或y&1
     7             x >>= 1;//x右移一位
     8             y >>= 1;
     9         }
    10         while(x){
    11             dis += (x & 1);
    12             x >>= 1;
    13         }
    14         while(y){
    15             dis += (y & 1);
    16             y >>= 1;
    17         }
    18         return dis;
    19     }
    20 };

    两个数都不为0的话,比较两个数的最后一位,x&1得到x对应二进制的最后一位,通过异或运算判断最后一位是否相同,不同加1,相同加0.循环结束后只有一个数不为0,另外一个数为0,此时0对应的所有二进制都为0,此时只要计算不为0的数对应二进制1的个数。

    改进:上面用了三个while,用一个就够了:

     1 class Solution {
     2 public:
     3     int hammingDistance(int x, int y) {
     4         int dis = 0;
     5         while(x || y){//或运算,只要有一个不为0就进行此循环
     6             dis += (x & 1) ^ (y & 1);
     7             x >>= 1;
     8             y >>= 1;
     9         }
    10         return dis;
    11     }
    12 };

    改进:显然,只要将x和y异或,得到数对应的二进制位为1的个数即为x和y的汉明距离。

     1 class Solution {
     2 public:
     3     int hammingDistance(int x, int y) {
     4         int count = 0;
     5         int t = x ^ y;
     6         while(t){
     7             count += t & 1;
     8             t >>= 1;
     9         }
    10         return count;
    11     }
    12 };
     
  • 相关阅读:
    标记不同浏览器的Burp Suite 插件
    60%配列机械键盘客制化清单
    配合mitmproxy使用自动化工具测试阿里云API网关接口
    CORS & CSP笔记
    fmex挂单挖矿
    使用SPLUNK进行简单Threat Hunting
    Mac最新系统bssdb BUG
    技巧之如何快速使用websocket来监控标准输出
    币早知道夺宝题--以太坊题解题方法
    发行NEO的NEP-5合约代币
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/6341493.html
Copyright © 2011-2022 走看看