LeetCode—461. Hamming Distance—Analysis and Code (Java)

LeetCode—461. Hamming Distance [Hamming Distance]—Analysis and Code [Java]

1. Title

The Hamming distance between two integers refers to the number of positions where the two numbers correspond to different binary bits.
Given two integers x and y, calculate the Hamming distance between them.

Note:
0 ≤ x, y <2^31.

Example:

输入: x = 1, y = 4

输出: 2

解释:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

上面的箭头指出了对应二进制位不同的位置。

Source: LeetCode
Link: https://leetcode-cn.com/problems/hamming-distance
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, analysis and code

1. Bit operation

(1) Thinking

First, extract the different positions of the binary bits through exclusive OR operation, and then judge and count bit by bit.

(2) Code

class Solution {
    
    
    public int hammingDistance(int x, int y) {
    
    
        int ans = 0, xor = x ^ y;
        while (xor != 0) {
    
    
            if ((xor & 1) == 1)
                ans++;
            xor >>= 1;
        }
        return ans;
    }
}

(3) Results

Execution time: 0 ms, beating 100% of users
in all Java submissions ; memory consumption: 35.7 MB, beating 30.49% of users in all Java submissions.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/112688735