Solution with XOR & counting 1s - Java Solution.

  • 0
    class Solution {
        public int hammingDistance(int x, int y) {
            int z=x^y;     //xor will put 1s at different bits; put 0s at same bit.        
            return Integer.toBinaryString(z).length() - Integer.toBinaryString(z).replace("1","").length();  // found the length of xor's binaryString's result, the length of string after removing 1's. Found the difference between those 2 lengths.

Log in to reply

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