This article is participating in the “Java Theme Month – Java Brush questions punch card”, see the activity link for details

I. Title Description:

Ii. Analysis of Ideas:

Today to share with you is an easy problem, find the hamming distance of two integers. The Hamming distance refers to the number of different binary positions corresponding to two numbers.

Direct bitwise traversal is different

The first straightforward idea is to directly compare the binary bits of two integers in bitwise. Since it is a 32-bit int, it is shifted 32 times, finding the least significant digit each time, then xor the least significant digit, and getting 1 indicates that this digit is different. Once the traversal is complete, the result is available.

function hammingDistance($x.$y) {
        $ret = 0;
        for ($i = 0; $i < 32; $i{+ +)$x1 = ($x >> $i) & 1;
            $y1 = ($y >> $i) & 1;
            if ($x1 ^ $y1) {
                $ret++;
            }
        }

        return $ret;
    }
Copy the code

Another way to think about it

Another way of thinking is to find the xOR result of two numbers first, and then find the number of the number 1 in this result, which is the Hamming distance. Finding the number of 1’s is recommended by recitation.

class Solution {

    / * * *@param Integer $x
     * @param Integer $y
     * @return Integer
     */
    function hammingDistance($x.$y) {
        $temp = $x ^ $y;
        $res = 0;
        while($temp) {
            $temp = $temp & ($temp-1);
            $res+ +; }return $res; }}Copy the code

Iii. AC Code:

Iv. Summary:

Today’s topic is relatively simple, investigate the bit operation, which uses the number of a binary representation of the median 1 is more common, it is recommended to memorize the relevant code directly.