Created
February 25, 2018 00:31
-
-
Save dilanshah/5307d2f8f9cfe803750b31286a19dc65 to your computer and use it in GitHub Desktop.
461. Hamming Distance on Leetcode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
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. | |
Input: x = 1, y = 4 | |
Output: 2 | |
Explanation: | |
1 (0 0 0 1) | |
4 (0 1 0 0) | |
↑ ↑ | |
Sudocode: | |
- Want to convert the int to binary format | |
- Want to test for condition that one is larger than the other | |
- Want to return the number of mismatches | |
The above arrows point to positions where the corresponding bits are different. | |
''' | |
class Solution: | |
def hammingDistance(self, x, y): | |
""" | |
:type x: int | |
:type y: int | |
:rtype: int | |
""" | |
s1, s2 = format(x,'032b'), format(y,'032b') | |
assert len(s1) == len(s2) | |
return sum(c1 != c2 for c1, c2 in zip(s1, s2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment