Hamming Distance Java Solution


  • 0
    K
    public int hammingDistance(int x, int y) {
    		int m = x^y;
    		int c = 0;
    		for(int i=1;i<32;i++){
    			if(((1<<i) & m) != 0){
    				c++;
    			}
    		}
    		return c;
    	}
    

    The idea is base on XOR operation, to find which bit is different. Then, use AND operation to travel every position of the bits and count if there is 1 on the bit.


Log in to reply
 

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