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:
复制代码
class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        out(0, 0)=0
        out(0, 1)=1
        out(1, 0)=1
        out(1, 1)=0
        out(2, 1)=2
        out(4, 1)=2
        out(0xffffffff, 0)=31?
        1100 & 1011 = 1000
        """
        z = x ^ y
        res = 0
        while z:            
            res += 1
            z = z & (z-1)
        return res
        
复制代码

解法2:

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

因为:

>>> bin(12)
'0b1100'
>>> '0b1100'.count('1')
2
>>> 'abcb'.count('b')
2

 

解法3:

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.

Code:

ans = 0
while x or y:
  ans += (x % 2) ^ (y % 2)
  x /= 2
  y /= 2
return ans

比较笨拙,其实 (x & 1) ^ (y & 1), x>>1,y>>1 更好!单独判断某位是否为1移位即可,当然用%2也可以。

        res = 0
        while x or y:
            res += (x&1) ^ (y&1)
            x = x>>1
            y = y>>1
        return res

 

posted @   bonelee  阅读(179)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2017-02-27 linkedin databus介绍——监听数据库变化,有新数据到来时通知其他消费者app,新数据存在内存里,多份快照
2017-02-27 ES忽略TF-IDF评分——使用constant_score
2017-02-27 ES设置字段搜索权重——Query-Time Boosting
2017-02-27 lucene内置的评分函数
2017-02-27 ES搜索排序,文档相关度评分介绍——Vector Space Model
2017-02-27 ES搜索排序,文档相关度评分介绍——TF-IDF—term frequency, inverse document frequency, and field-length norm—are calculated and stored at index time.
2017-02-27 ES搜索排序,文档相关度评分介绍——Field-length norm
点击右上角即可分享
微信分享提示