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

  • 相关阅读:
    Solon 特性简集,相较于 Springboot 有什么区别?
    Solon 1.2.12 发布,新的惊喜
    Springboot mini
    Springboot mini
    Springboot mini
    Springboot mini
    Springboot mini
    Springboot mini
    Springboot mini
    CODING 静态网站服务升级,快速、稳定、高拓展!
  • 原文地址:https://www.cnblogs.com/prmlab/p/6964661.html
Copyright © 2011-2022 走看看