• 461. Hamming Distance


    https://leetcode.com/problems/hamming-distance/#/description

    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.



    Sol:

    The hamming distance is the number of different digits of two numbers in binary digit.   

    Get every mod of x and y divided by 2, and add one to the answer when they are different.

    class Solution(object):
        def hammingDistance(self, x, y):
            """
            :type x: int
            :type y: int
            :rtype: int
            """
            
            # We can find the i-th bit (from the right) of a number by dividing by 2 i times, then taking the number mod 2.
    
            # Using this, lets compare each of the i-th bits, adding 1 to our answer when they are different.
            ans = 0
            while x or y:
                ans += ( x%2 ) ^ ( y%2 )
                x /= 2
                y /= 2
            return ans

    Note:

    1 x ^ y,  where ^ means exclusive or.

    return 1 only when two bits are different.

    1 0 ==> 1

    0 1 ==> 1

    0 0 ==> 0

    1 1 ==> 0

    2 x & y, where & means and.

    return 1 only when two bits are 1.

    1 1 ==> 1

    1 0 ==> 0

    0 1 ==> 0

    0 0 ==> 0

    3 This problem is clearly about bit manipulation. Think of  bit operators. 

    4 The end condition of division is the last dividend goes down to zero. 

  • 相关阅读:
    Spring自动代理机制
    JUnit4 详解
    struts2 OGNL
    loj4j的配置跟使用
    junit浅学笔记二
    shell变量设置
    zookeeper使用
    [zz]Linux kernel map
    glog 使用中存在的问题
    shell中特殊字符(串)
  • 原文地址:https://www.cnblogs.com/prmlab/p/6964661.html
Copyright © 2020-2023  润新知