Hamming Distance Java Solution

  • 1
    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){
    		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.

  • 0

    @kevinbauer Hello Kevin, I don't quite understand that why your looping index i is started from 1 rather than 0. In you code, the least significant bit of m is not & with 1. Please let me know where I am wrong. Thanks!

Log in to reply

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