在不使用 C++ 中的 XOR 運算子的情況下查詢兩個數字的 XOR
在此問題中,我們得到整數值 A 和 B。我們的任務是在不使用 XOR 運算子的情況下查詢兩個數字的 XOR。
我們舉個例子來理解這個問題,
Input : A = 4, B = 5 Output : 1
解決方案方法
解決此問題的一種方法是將數字轉換為其各自的二進位制數,然後根據此表執行按位運算。
| A | B | 輸出 |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
這將返回結果。為此,我們將使用按位運算。
示例
說明我們解決方案工作原理的程式
#include <iostream>
using namespace std;
int calcXORwoOperator(int a, int b){
int xorVal = 0;
for (int i = 31; i >= 0; i--){
bool val1 = a & (1 << i);
bool val2 = b & (1 << i);
bool xorBit = (val1 & val2) ? 0 : (val1 | val2);
xorVal <<= 1;
xorVal |= xorBit;
}
return xorVal;
}
int main(){
int a = 4, b = 5;
cout<<"XOR of the numbers is "<<calcXORwoOperator(a, b);
return 0;
}輸出
XOR of the numbers is 1
交替方法 −
查詢異或的另一種方法是在兩個數字中逐一比較存在的位,並對它們執行等效於 XOR 的運算。
表示式 (a | b) - (a & b) 等於 a^b。因此,我們將執行此操作。從而找到兩個數字 a 和 b 的 XOR。
示例
說明我們解決方案工作原理的程式
#include <iostream>
#include <bitset>
using namespace std;
int calcXORwoOperator(int a, int b) {
return (a | b) - (a & b);
}
int main(){
int a = 4;
int b = 5;
cout<<"The XOR of both numbers is "<<(bitset<8>(calcXORwoOperator(a, b)));
return 0;
}輸出
The XOR of both numbers is 00000001
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP