0ms C two line solution


  • 2
    L
    int hammingDistance(int x, int y) {
    	if((x^y)==0) return 0;
    	return (x^y)%2 + hammingDistance(x/2,y/2);
    }
    

  • 0
    G

    The idea is good, it used bitwise operation methods to get the answer.

    int hammingDistance(int x, int y) {
    	if((x^y)==0) return 0;
    	return (x^y) % 2 + hammingDistance(x/2, y/2);
    }
    

    For example 14=1110 there are 3 1s in 14. You can use bitwise operation << to divide the number with 2 if the number is an even number else minus 1 and then continue divide 2 until the number is 0.


Log in to reply
 

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