Golang concise solution


  • 0

    Just mark 1 only a position that a bit of x and y are different by using XOR.
    After that, just count a number of 1 of the result of XOR. That's it.

    func hammingDistance(x int, y int) int {
        xor := x ^ y
        count := 0
        
        for {
            if xor == 0 {
                break
            }
            xor = xor & (xor - 1) // reset the rightmost "1" bit
            count++
        }
        return count
    }
    

Log in to reply
 

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