[With Golang brush Leetcode 1] 461. Hamming Distance

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Title Description

https://leetcode.com/problems/hamming-distance/description/
The Hamming distance between and integers is the number of positions at which, the corresponding bits is different.
Given 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 is different.

Thinking of solving problems

This topic examines the knowledge point is an XOR operator ^, the idea is to solve the problem is the X, y two number of different or operation, and then statistics 1 occurrences.

Related knowledge points

In this topic, the meaning of Hamming distance is two integers of different bits and.
Xor operator is "same as 0, different from 1"

Golang Code

Hammingdistance.go

package _461_HammingDistancefunc 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)}

Test code

Hammingdistance_test.go

package _461_HammingDistanceimport (    "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)    }}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.