leetcode Daily Challenge on July 5th, 2020.
Difficulty : Easy
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.
- 0 ≤ x, y < 231.
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.
- mine
- Java
Runtime: 0 ms, faster than 100.00%, Memory Usage: 37.9 MB, less than 10.92% of Java online submissions
// O(logN)time O(1)space // N = x ^ y; public int hammingDistance(int x, int y) { int res = 0; x = x ^ y; int count = 1; while(count < 32){ res += (x & 1); x = x >> 1; count++; } return res; }
- Java
-
the most votes
Runtime: 0 ms, faster than 100.00%, Memory Usage: 33.2 MB, less than 5.09% of Java online submissions
public int hammingDistance(int x, int y) { return Integer.bitCount(x ^ y); }