Teaching Kids Programming: Videos on Data Structures and Algorithms
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: 2Explanation:
1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑The above arrows point to positions where the corresponding bits are different.
Compute the Hamming Distance
The XOR of two integers, will set 1 to those bits of different values. Thus, we can use XOR and count the value of 1’s bits: Teaching Kids Programming – Compute the Number of Set Bits in an Integer
1 2 3 4 5 6 7 8 | class Solution: def hammingDistance(self, x: int, y: int) -> int: n = x ^ y a = 0 while n > 0: a += 1 n &= (n - 1) return a |
class Solution: def hammingDistance(self, x: int, y: int) -> int: n = x ^ y a = 0 while n > 0: a += 1 n &= (n - 1) return a
Hamming Weight / Hamming Distance Algorithms
Here are the posts related to Hamming Distance (XOR, The number of different bits):
- A faster approach to count set bits in a 32-bit integer
- Teaching Kids Programming – Minimum Bit Flips to Convert Number (Hamming Distance)
- GoLang: Compute the Hamming Distance
- How to Sort List by Hamming Weight in C++?
- Teaching Kids Programming – Compute the Hamming Distance of Two Integers
- Compute the Total Hamming Distance between All Pairs of Integers
- The Hamming Distance Implementation in Javascript
- Hamming Distance between Two Integers
- Compute Number of 1’s Bits in C/C++
- Teaching Kids Programming – Sort List by Hamming Weight
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
531 wordsloading...
Last Post: Teaching Kids Programming - Python Function to Check If Valid IPv4 Address
Next Post: K Distinct Window Algorithm by Sliding Window