↓Skip to main content
  1. LeetCode/

LeetCode 461: Hamming Distance

·1 min· ·
LeetCode Easy Bit-Manipulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-24

  • Submissions: Accepted ×2

Approach
#

XOR is 1 exactly where the bits differ, so the Hamming distance is the number of 1s in x ^ y (Bit Manipulation). Count them with bin(z).count("1") or by repeating z &= z - 1, which clears the lowest 1 each time.

My Solution
#

class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        z, count = x ^ y, 0
        while z:
            z &= z - 1
            count += 1
        return count

Complexity
#

Time O(number of bits), space O(1).

Mistakes to Avoid
#

  • z & (z - 1) clears one 1 per step, so the loop runs once per set bit.

Interview Explanation
#

XOR marks differing bits, so I compute x XOR y and count its 1s by clearing one at a time with z & (z - 1). Time is the number of set bits.

Related

LeetCode 136: Single Number
·1 min
LeetCode Easy Array Bit-Manipulation
LeetCode 136 note: x ^ x = 0 and x ^ 0 = x, so XOR everything; pairs cancel and the single number remains
LeetCode 476: Number Complement
·1 min
LeetCode Easy Bit-Manipulation
LeetCode 476 note: build an all-ones mask as long as num; num ^ mask is the complement
LeetCode 342: Power of Four
·1 min
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 note: confirm a power of two, then that the single 1 sits at an even position: n & 0x55555555 != 0, or n % 3 == 1
LeetCode 389: Find the Difference
·1 min
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
LeetCode 389 note: t has one extra character; XOR every character of both strings, pairs cancel, and the extra one remains
LeetCode 405: Convert a Number to Hexadecimal
·2 mins
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 note: add 2^32 to a negative number to get its two’s complement, then take 4 bits at a time (% 16); handle 0 separately
LeetCode 231: Power of Two
·2 mins
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 231 note: a power of two has exactly one set bit, and n & (n - 1) clears the lowest one, so the result is 0 exactly then; n must be positive