当前位置:网站首页>Leetcode XOR operation

Leetcode XOR operation

2022-04-23 19:43:00 Garrick doesn't want 996

  • The rule of XOR operation is that the result of two identical numbers after XOR is 0,0 And others 0 The result after the number XOR of is the latter , And XOR operation supports commutative law and associative law , With these definitions, some algorithms can skillfully use XOR to solve problems .

  • Addition operation

    XOR may not be used + Number to add two numbers , The result of the XOR of two numbers is the result of their addition

#include <iostream>
using namespace std;

int main() {
	int single =20;
	single ^=10;
	cout<<single;
	return 0;
}

The output is 30

  • Only once
    It is also the most magical function , It's also because of this question that I wrote this ,LeetCode Last question :
     Insert picture description here
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int temp = 0;
        for(int num:nums){
            temp = temp ^ num;
        }
        return temp;
    }
};
  • XOR has three properties .
    Any number and 0 Do exclusive or operations , The result is still the original number , namely a⊕0=a.
    Any number is XOR with itself , The result is 0, namely a⊕a=0.
    XOR operation satisfies the exchange law and the combination law , namely a⊕b⊕a=b⊕a⊕a=b⊕(a⊕a)=b⊕0=b

版权声明
本文为[Garrick doesn't want 996]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231942178113.html