Hamming Distance Java Solution


  • 0
    F
        public  int solution(int x, int y) {
            int z = x ^ y;
            int sum = 0;
            while (z > 0) {
                sum += z & 1;
                z = z >> 1;
            }
            return sum;
        }
    

    or

      public static int solution(int x, int y) {
            return Integer.bitCount(x ^ y);
        }
    

    bitCount code

       public static int bitCount(int i) {
            // HD, Figure 5-2
            i = i - ((i >>> 1) & 0x55555555);
            i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
            i = (i + (i >>> 4)) & 0x0f0f0f0f;
            i = i + (i >>> 8);
            i = i + (i >>> 16);
            return i & 0x3f;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.