Hamming Distance

Hamming Distance

package leetcode

import "fmt"
import "math/big"

func HammingDistance(x int, y int) int {
	bin, diff := fmt.Sprintf("%b", x^y), 0
	for i := 0; i < len(bin); i++ {
		if string(bin[i]) == "1" {
			diff++
		}
	}
	return diff
}

func HammingDistance2(x int, y int) int {
	var count int
	z := x ^ y
	d := big.NewInt(int64(z))
	for _, x := range d.Bits() {
		for x != 0 {
			x &= x - 1
			count++
		}
	}
	return count
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注