【LeetCode】【Python】461.Hamming Distance

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ww1473345713/article/details/82263498

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()函数返回字符串中某个字符出现的个数.

猜你喜欢

转载自blog.csdn.net/ww1473345713/article/details/82263498
今日推荐