Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.

I. Problem description

The Hamming distance between two integers refers to the number of different positions of the two numbers corresponding to the binary bits.

Given two integers x and y, calculate and return the Hamming distance between them.

Title link: Hamming distance.

Two, the title requirements

Sample 1

Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0 0) ↑ arrows indicate the different locations of the corresponding binary bits.Copy the code

The sample 2

Input: x = 3, y = 1 Output: 1Copy the code

inspection

2. It is recommended to take 5 to 20 minutesCopy the code

Third, problem analysis

This is the third question in bit operation. If you do not know the relevant knowledge points of bit operation, you can see this article.

Day 45: Bit operation

What is the Hamming distance? Simply speaking, it is to convert two base digits into base two and count the number of 1’s above different positions. How can we gradually move this problem closer to the bit operation?

Different positions, what do you mean different positions, if the same position is 1, then you don’t count. Counting only starts when one is 1 and the other is 0 in the same position. Isn’t that the sum of bitwise operations?

Four, coding implementation

class Solution {
public:
    int hammingDistance(int x, int y) {
        int i,ans=0;// Initialize the data
        for(i=0; i<32; i++)// 32-bit loop judgment
        {
            if((x^y)&1<<i)// Start to query the number of 1
            {
                ans++;// counter ++}}return ans;// Output the result}};Copy the code

V. Test results