Java 3-line super fast solution


  • 0
    M
    public class Solution {
        public int hammingDistance(int x, int y) {
            int count = 0;
            for(int xor = x^y; xor != 0; xor = (xor) & (xor-1)) count++;
            return count;
        }
    }
    

    xor = (xor) & (xor-1) flips the rightmost set bit. Therefore, if xor has m bits set to 1, the for-loop iterates only m times.


Log in to reply
 

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