美文网首页LeetCode By Go
[LeetCode By Go 1]461. Hamming D

[LeetCode By Go 1]461. Hamming D

作者: miltonsun | 来源:发表于2017-08-14 16:10 被阅读48次

    题目描述

    https://leetcode.com/problems/hamming-distance/description/
    The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
    Given two integers x and y, calculate the Hamming distance.
    Note:
    0 ≤ x, y< 2^31.
    Example:

    Input: x = 1, y = 4
    Output: 2
    Explanation:

    1 (0 0 0 1)
    4 (0 1 0 0) 
           ↑ ↑
    

    The above arrows point to positions where the corresponding bits are different.

    解题思路

    此题考察的是知识点是异或运算符^,解题的思路就是将x,y两数进行异或运算,然后统计1的出现次数。

    相关知识点

    在本题目中,汉明距离的含义是两个整数的不同二进制位的和。
    异或运算符作用为“相同出0,不同出1”

    Golang代码

    hammingDistance.go

    package _461_HammingDistance
    
    func HammingWeight(z int) (w int){
    
        for z > 0 {
            tmp := z % 2
            if 1 == tmp {
                w++
            }
            z = z /2
        }
    
        return w
    }
    func HammingDistance(x int, y int) int {
    
        z := x ^ y
    
        return HammingWeight(z)
    }
    

    测试代码

    hammingDistance_test.go

    package _461_HammingDistance
    import (
        "testing"
    )
    
    func Test_HammingDistance(t *testing.T) {
        ret := HammingDistance(1, 4)
        if 2 != ret {
            t.Errorf("test fail, want 2, get %+v\n", ret)
        } else {
            t.Logf("test pass, want 2, get %+v\n", ret)
        }
    }
    

    相关文章

      网友评论

        本文标题:[LeetCode By Go 1]461. Hamming D

        本文链接:https://www.haomeiwen.com/subject/holwlxtx.html