Through Leetcode learning bit arithmetic and its go implementation

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

Problem description

461. Hamming Distance
That is, the number of binary corresponding digits of two positive integers is different.

Principle explanation

In terms of the problem description, the most intuitive solution is that the decimal number is first turned into binary, and then the same number is the same, different counters accumulate, the value of the final counter is Hamming Distance .

Optimization scheme: First ^ operation, the number of bits of the result of the operation to traverse, 1 the counter accumulated

Based on this idea, there is a need to use the 异或运算 and 位运算 .

Xor ^ and XOR or non-

XOR algorithm: The same is zero, the difference is one.
XOR algorithm: The same as one, the difference is zero.
That

输入A: 1 0 1 0输入B: 1 1 0 0异或运算结果: 0 1 1 0异或非(同或)运算结果:1 0 0 1

Move left << and right >>

Move left

    • The right-hand vacated bits are filled with 0
    • High-left-shift overflow discards the high

Move right

    • The left vacated bits are filled with 0 or 1. Positive numbers are filled with 0, negative numbers are filled with 1
    • The low-right-shift overflow discards the bit

Code implementation

func hammingDistance(x int, y int) int {    counter := 0    tmp := x ^ y    t := 1        for i := uint(0); i < 32 && t > 0; i++ {        t = tmp >> i        counter += (tmp >> i) & 1    }    return counter}

Reference

    1. Baidu Wikipedia or not
    2. Baidu Encyclopedia Bit arithmetic

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.