"100 Lectures on Algorithm Zero Basics" (Lesson 46) Introduction to Bit Operation (Exclusive OR)

write in front

XOR

First come an XOR truth table

x and x^y
0 0 0
1 0 1
0 1 1
1 1 0

From the above table, we can actually dig out a lot of properties.

  1. The XOR of the same two numbers must be 0
  2. The XOR of any number and 0 must be 0
  3. The XOR value can be used to find the different bits in the binary bits of two numbers

Simple application

The most classic application of XOR is to exchange the values ​​of two variables. In fact, it also uses the property that the XOR of the same two numbers is equal to 0. code show as below:

a=a^b;
b=a^b;
a=a^b;

homework

136. Numbers that only appear once

Directly use the property that the sum of two numbers is 0

class Solution {
    
    
public:
    int singleNumber(vector<int>& nums) {
    
    
        int sum=0;
        for(auto t:nums) sum^=t;
        return sum;
    }
};

190. Reversing Bits

How many binary digits are in a number from the back to the front, a number has been pushed forward by one and added

class Solution {
    
    
public:
    uint32_t reverseBits(uint32_t n) {
    
    
        uint32_t ans=0;
        for(int i=0;i<32;i++) {
    
    
            ans=(ans<<1)|(n&1);
            n>>=1;
        }
        return ans;
    }
};

461. Hamming distance

The number of 1s in the XOR sum of two numbers is the number of different bits in the binary

class Solution {
    
    
public:
    int lowbit(int x) {
    
    
        return x&-x;
    }
    int hammingDistance(int x, int y) {
    
    
        int t=x^y,cnt=0;
        while(t) {
    
    
            t^=lowbit(t);
            cnt++;
        }
        return cnt;
    }
};

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324122266&siteId=291194637