Skip to content
the poor coder

Leetcode - Hamming Distance Solution

Poor Man
Published
Updated
Reading time
1 min read

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, return the Hamming distance between them.

Example 1:

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

Example 2:

Text
Input: x = 3, y = 1
Output: 1

Constraints:

  • 0 <= x, y <= 231 - 1

Solution in Python#

Python
class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        x_bin = bin(x)[2:].zfill(32)
        y_bin = bin(y)[2:].zfill(32)
        return sum(1 for x,y in zip(x_bin,y_bin) if x!=y)

Keep going

2021

Leetcode - Power of Four Solution

Given an integer n, return true if it is a power of four. Otherwise, return false. An integer n is a power of four, if there exists an integer x such that n == 4x. Example 1: Example 2: Example 3: Constraints: -231 <= n…

ESC