Skip to content

[461] Hamming Distance

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

  • algorithms
  • Easy (69.56%)
  • Source Code: 461.hamming-distance.py
  • Total Accepted: 229.6K
  • Total Submissions: 327.2K
  • Testcase Example: '1\n4'

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 < 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.

python
class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        sx, sy = bin(x), bin(y)

        sx, sy = sx[2:], sy[2:]
        lenx, leny = len(sx), len(sy)

        if lenx > leny:
            sx, sy = sy, sx
            lenx, leny = leny, lenx

        # print(lenx, leny)
        sx = '0' * (leny-lenx) + sx

        cnt = 0
        # print(sx, sy)
        for i in range(leny):
            if sx[i] != sy[i]: cnt += 1

        return cnt

#
# s = Solution()
# print s.hammingDistance(3, 1)
#

Last updated: