Skip to content

Latest commit

 

History

History
68 lines (55 loc) · 1.33 KB

461. Hamming Distance.md

File metadata and controls

68 lines (55 loc) · 1.33 KB

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.

Note:

  • 0 ≤ x, y < 231.

Example:

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.

Solution

  • 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;
        }
        

  • 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);
      }