C++ 中一個範圍中一對數的最大異或值
問題陳述
給定一個範圍 [L,R],我們需要找出這兩個整數,使得它們在所有可能的選擇的兩個整數中異或值最大
如果給定的範圍是 L = 1 且 R = 21,則輸出將為 31,因為−31 是 15 和 16 的異或值,並且在範圍內是最大的值。
演算法
1. Calculate the (L^R) value 2. From most significant bit of this value add all 1s to get the final result
示例
#include <bits/stdc++.h> using namespace std; int getMaxXOR(int L, int R){ int LXR = L ^ R; int msbPos = 0; while (LXR) { msbPos++; LXR >>= 1; } int maxXOR = 0; int two = 1; while (msbPos--) { maxXOR += two; two <<= 1; } return maxXOR; } int main(){ int L = 1; int R = 21; cout << "Result = " << getMaxXOR(L, R) << endl; return 0; }
輸出
當你編譯並執行以上程式時,它會生成以下輸出 -
Result = 31
廣告