Leetcode algorithm question 1: How many bits of two binary numbers are different? The home of XOR, displacement, and computation

Source: Internet
Author: User

/*
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.

Note:
0≤x, y < 231.

Example:

input:x = 1, y = 4

Output:2

Explanation:

1 (0 0 0 1)

4 (0 1 0 0)

The above arrows point to positions where the corresponding bits is different.
*/
int hammingdistance (int x, int y) {

}

Test instructions: Enter two int to find the number of different bits of the binary number of the two numbers.

Method One:

* Can take advantage of an XOR feature: The same is 0, the difference is 1. The two-digit XOR, and then the result of a few 1.

?? * How can I tell how many 1 are in int?

???? * You can divide this number by 2 and record the number of modulo 2 as 1 until the number changes to 0. That is, the process of simulating the binary number of the transfer.

Method Two:

* First different or.

* How to judge a few 1?

?? * Move right one bit, then left one bit, if not equal to the original number, there is a 1. The process of turning the binary number is also simulated.

?? * Move right one position except 2.

Method Three:

* First different or.

* How to judge a few 1?

while(n) {    c++;    n=n&(n-1);}

n& (n-1) is the least 1 of N is changed to 0.

#include <stdio.h>int Hammingdistance (IntXIntY) {int r =x ^Yint cnt =0;while (R >0) {if (r%2 = =1) {cnt + +;} r = r/2; }return CNT;}int HammingDistance2 (IntXIntY) {int r=x^Yint cnt =0;while (R) {if ((r>>1) <<1! = r) {cnt + +;} r >>=1; }return CNT;}int hammingDistance3 (int x, Span class= "Hljs-keyword" >int y) {int r=x^y; int cnt=0; while (r) {cnt + +; r=r& (R-1);} return cnt;} int Main (int argc, char *argv[]) {printf ( "%d\n", HammingDistance3 (1,4)); return 0;}         

Leetcode algorithm question 1: How many bits of two binary numbers are different? The home of XOR, displacement, and operation

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.