C++の排他的論理和演算子
前言:leetcodeをしてMissing NumberとSingle Number IIII問題に出会う
一、「排他的OR」演算子(∧)
XOR演算子とも呼ばれます.ルール:同じ0、異なる1,0∧0=0、0∧1=1,1∧0=1,1∧1=0
適用:
(1)0相∧,原値保持
(2)一時変数なしで2つの値を交換する
(
3)自分と向き合う
∧,値0
二、leetcode No 268.Missing Number
Question:
Given an array containing n distinct numbers taken from
For example, Given nums =
Algorithm:Bit Manipulation
0-nの数異をnumsの数異とすると,Missing Numberが得られる(Missing Numberを除いては自分が一度異或した)
Submitted Code:
三、leetcode No 136.Single Number
Question:
Given an array of integers, every element appears twice except for one. Find that single one.
Algorithm:Bit Manipulation
すべての要素
Submitted Code:
四、leetcode No 260.Single Number III
Question:
Given an array of numbers
For example:
Given
Algorithm:Bit Manipulation
1、Single Numberの方法に従って、すべての元素に対して排他的または排他的であれば、この2つの元素排他的または値xor_が得られる.two
2、2つの要素をどのように分けるか、値の異なるビットが1であるため、xor_を見つけることができます.twoの最後の1(-xor_twoはその符号化)は、2つの要素を区別し、2つの配列をそれぞれ異ならせます.
Submitted Code:
一、「排他的OR」演算子(∧)
XOR演算子とも呼ばれます.ルール:同じ0、異なる1,0∧0=0、0∧1=1,1∧0=1,1∧1=0
適用:
(1)0相∧,原値保持
(2)一時変数なしで2つの値を交換する
a = a^b;
b = b^a;
a = a^b;
(
3)自分と向き合う
∧,値0
二、leetcode No 268.Missing Number
Question:
Given an array containing n distinct numbers taken from
0, 1, 2, ..., n
, find the one that is missing from the array. For example, Given nums =
[0, 1, 3]
return 2
. Algorithm:Bit Manipulation
0-nの数異をnumsの数異とすると,Missing Numberが得られる(Missing Numberを除いては自分が一度異或した)
Submitted Code:
class Solution {
public:
int missingNumber(vector& nums) {
int xor_num = 0;
int length = nums.size();
while(length!=0)
{
xor_num ^= length;
length--;
}
for(int i : nums)xor_num ^= i;
return xor_num;
}
};
三、leetcode No 136.Single Number
Question:
Given an array of integers, every element appears twice except for one. Find that single one.
Algorithm:Bit Manipulation
すべての要素
Submitted Code:
class Solution {
public:
int singleNumber(vector& nums) {
int x = 0;
for(int i=0;i
四、leetcode No 260.Single Number III
Question:
Given an array of numbers
nums
, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. For example:
Given
nums = [1, 2, 1, 3, 2, 5]
, return [3, 5]
. Algorithm:Bit Manipulation
1、Single Numberの方法に従って、すべての元素に対して排他的または排他的であれば、この2つの元素排他的または値xor_が得られる.two
2、2つの要素をどのように分けるか、値の異なるビットが1であるため、xor_を見つけることができます.twoの最後の1(-xor_twoはその符号化)は、2つの要素を区別し、2つの配列をそれぞれ異ならせます.
Submitted Code:
class Solution {
public:
vector singleNumber(vector& nums) {
int xor_two = nums[0];
int last_bit = 0;
vector result = {0,0};
for(int i=1;i