当前位置:网站首页>Leetcode 461 Hamming distance

Leetcode 461 Hamming distance

2022-07-06 11:00:00 Sanli akaman

subject

Between two integers Hamming distance It refers to the number of different positions of the two numbers corresponding to the binary bits .
Here are two integers x and y, Calculate and return the Hamming distance between them .

Example

 Insert picture description here

Best code

package com.vleus.algorithm.bit_operator;

/** * @author vleus * @date 2021 year 08 month 03 Japan  22:35 */
public class HammingDistance {
    

    // Method 1 : Exclusive or : Inventory adjustment statistics 1 The number of 
    public int hammingDistance(int x, int y) {
    
        return Integer.bitCount(x ^ y);
    }

    // Method 2 : Custom implementation statistics 1 The number of , Move right bit by bit 
    public int hammingDistance2(int x, int y) {
    
        int xor = x ^ y; // Get XOR result 
        int count = 0; // Save the current 1 The number of 

        // Move right bit by bit , Until the result is 0
        while (xor != 0) {
    
            // If the last one is 1,count++
            if ((xor & 1) == 1) {
    
                count++;
            }
            xor >>=1; // Move right 1 position 
        }

        return count;
    }

    public int hammingDistance3(int x, int y) {
    

        int xor = x ^ y; // Get XOR result 
        int count = 0; // Save the current 1 The number of 

        // Fast displacement , Look for the current rightmost one every time 1, Eliminate directly 
        while (xor != 0) {
    
            xor = xor & xor - 1;
            count++;
        }

        return count;
    }
}
原网站

版权声明
本文为[Sanli akaman]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060912267035.html