• [LeetCode] 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 < 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的数量累加起来就是汉明距离。

    Java:

    public int hammingDistance(int x, int y) {  
            int res = x ^ y;  
            int count = 0;  
            for (int i = 0; i < 32; i++) {  
                if ((res & 1) != 0)  
                    count++;  
                res >>= 1;  
            }  
            return count;  
    }    

    Python:

    class Solution(object):
        def hammingDistance(self, x, y):
            """
            :type x: int
            :type y: int
            :rtype: int
            """
            distance = 0
            z = x ^ y
            while z:
                distance += 1
                z &= z - 1
            return distance
    

    Python:

    class Solution(object):
        def hammingDistance(self, x, y):
            """
            :type x: int
            :type y: int
            :rtype: int
            """
            return bin(x ^ y).count('1') 

    C++:

    class Solution {
    public:
        int hammingDistance(int x, int y) {
            int res = 0;
            for (int i = 0; i < 32; ++i) {
                if ((x & (1 << i)) ^ (y & (1 << i))) {
                    ++res;
                }
            }
            return res;
        }
    };
    

    C++:  

    class Solution {
    public:
        int hammingDistance(int x, int y) {
            int res = 0, exc = x ^ y;
            while (exc) {
                ++res;
                exc &= (exc - 1);
            }
            return res;
        }
    };
    

    C++:

    class Solution {
    public:
        int hammingDistance(int x, int y) {
            if ((x ^ y) == 0) return 0;
            return (x ^ y) % 2 + hammingDistance(x / 2, y / 2);
        }
    };
    

      

    类似题目:  

    [LeetCode] 191. Number of 1 Bits 二进制数1的个数

    All LeetCode Questions List 题目汇总

  • 相关阅读:
    OD 实验(十三)
    第一个 Windows 界面程序
    C 语言
    C 语言
    OD 实验(十二)
    PowerShell 常用命令
    OD 实验(十一)
    OD 实验(十)
    redis
    memcached缓存系统
  • 原文地址:https://www.cnblogs.com/lightwindy/p/9552031.html
Copyright © 2020-2023  润新知