461. Hamming Distance

Easy

Problem:

Take two integers as input and calculate how many bits are different.

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.

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

What to learn:

Number system in Python

In Python, binary, decimal, and hexadecimal numbers can be represented using bin(), int(), and hex(), respectively. The prefixes for binary and hexadecimal are 0b and 0x, respectively, which can be omitted. Both are returned as strings. However, if they are assigned without being processed as strings, they are internally converted and treated as decimals.

>>> bin(87)
'0b1010111'
>>> int('0b1010111', 2)
87
>>> id(87)
4547371104
>>> hex(87)
'0x57'
>>> c = 0x57
>>> c
87
>>> id(c)
4547371104

Solution:

The result of x^y XOR is an integer, so by converting it to binary using bin(), and then counting the total number of 1s, we get the number of differing positions, which is the Hamming distance.

class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        return bin(x ^ y).count('1')       

Last updated