HTMLify

LeetCode - Hamming Distance - Go
Views: 10 | Author: abh
func int_to_binary(n int) string {
    var b string = ""
    for ;n!=0; {
        if n % 2 == 0 {
            b = "0" + b
        } else {
            b = "1" + b
        }
        n = n / 2
    }
    return b
}
func hammingDistance(x int, y int) (hc int) {
    xb := int_to_binary(x)
    yb := int_to_binary(y)
    hc, max := 0, 0
    if len(xb) < len(yb) {
        max = len(yb)
    } else {
        max = len(xb)
    }
    lxb := len(xb)
    lyb := len(yb)
    var s string
    if lxb < lyb {
        s = xb
    } else {
        s = yb
    }
    for ;len(s)<max; {
        s = "0" + s
    }
    if lxb < lyb {
        xb = s
    } else {
        yb = s
    }
    for i:=0;i<max;i++ {
        if xb[i] != yb[i] {
            hc++
        }
    }
    return
}

Comments