Java solution using xor


  • 0
    R
    class Solution {
       public static  int hammingDistance(int x, int y) {
    
            // use bitwise xor operation 
            // xor returns 1 if the two bits are different else returns 0 
            int xorResult = x ^ y;
            
           // covert the xorResult binary string
            String xorResultBinaryStr = Integer.toBinaryString(xorResult);
    
            // get the char array to iterate to each character and find the how many 1s are there
            char[] resultChar = xorResultBinaryStr.toCharArray();
    
            int result = 0;
    
            for(char ch: resultChar)  {
    
                if (ch == '1') { // means bits are different
                    result += 1;
                }
            }
    
            return result;
    
        }
    }
    

Log in to reply
 

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