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:
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.
Example 2:
Input: x = 3, y = 1
Output: 10 <= x, y <= pow(2, 31) – 1
Hamming Distance in GoLang
XOR operation is same as other languages which uses ^ symbol. The Golang uses “for” keyword for a “while” loop. And the x&=x-1 removes the rightmost set bit.
1 2 3 4 5 6 7 8 9 | func hammingDistance(x int, y int) int { x ^= y var ans = 0 for x > 0 { ans += 1 x &= x - 1 } return ans } |
func hammingDistance(x int, y int) int { x ^= y var ans = 0 for x > 0 { ans += 1 x &= x - 1 } return ans }
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...
460 wordsloading...
Last Post: Teaching Kids Programming - K Numbers Greater Than or Equal to K using Binary Search
Next Post: Teaching Kids Programming - Insert a Node into a Binary Search Tree via Recursion