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