【LeetCode】【Python】461.Hamming Distance

461.Hamming Distance

question

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 ≤ x, y < 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. 

solution:

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

bin() 返回一个整数 int 或者长整数 long int 的二进制表示,类型为字符串。如bin(6)返回“0b101”,count()函数返回字符串中某个字符出现的个数.

全部评论

相关推荐

不愿透露姓名的神秘牛友
2025-12-18 11:21
优秀的大熊猫在okr...:叫你朋友入职保安,你再去送外卖,一个从商,一个从政,你们两联手无敌了,睁开你的眼睛看看,现在是谁说了算(校长在背后瑟瑟发抖)
选实习,你更看重哪方面?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务