Leetcode 461. Hamming Distance

Source: Internet
Author: User
Leetcode 461. Hamming Distance Topics

The Hamming distance between and integers is the number of positions at which, the corresponding bits is different.

Given integers x and y, calculate the Hamming distance.

Solution:

Class Solution {public
:
    int hammingdistance (int x, int y) {
        int z = x^y;
        int ans = 0;
        while (z) {
            ans++;
            Z &= z-1;
        }
        return ans;
    }
;

Writing this blog is mainly to record the clever use of Z-&= z-1-bit operations:
n = 10100 (binary), then (n-1) = 10011 = = "n& (n-1) = 10000
You can see that the original lowest bit of 1 is changed to 0. This can be used for the following applications:

1: Determine if a number is 2 operational (only the highest bit in the number of binary binary is 1)
n > 0 && ((N & (n-1)) = = 0)
2: Calculates the binary of a positive integer containing 1 of the number, for example in this code
3: Calculate the number of n! 2 of the mass factor
Easy to draw N. Number of factorization 2 = [N/2] + [N/4] + [N/8] + ....
Here's a simple example to deduce the process: N = 10101 (binary representation)
Now we track the highest bit of 1, regardless of the other bits assumed to be 0,
Then in
[N/2] 01000
[N/4] 00100
[N/8] 00010
[N/8] 00001
Then all add equals 01111 = 10000-1
The other bits are available: (10101)! The number of the mass factor 2 is 10000-1 + 00100-1 + 00001-1 = 10101-3 (the number of 1 in the binary representation)

The number of the mass factor 2 of the generalized n! is N-(the number of 1 in the N binary representation)

[1]n & (N-1)

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.