C ++中给定范围的最大按位与对

问题陈述

给定范围[L,R],任务是找到一个对(X,Y),使L≤X <Y≤R且X&Y在所有可能的对中最大,然后打印找到的对的按位与。

示例

如果L = 1且R = 10,则最大按位AND值为8,可以按如下方式形成-

1000 # Binary representation of 8
Bitwise AND
1001 # Binary representation of 9
----
1000 # Final result

算法

从L迭代到R,并检查每个可能的对的按位与,并在最后打印最大值

示例

现在让我们看一个例子-

#include <bits/stdc++.h>
using namespace std;
int getMaxBitwiseAndValue(int L, int R) {
   int maxValue = L & R;
   for (int i = L; i < R; ++i) {
      for (int j = i + 1; j <= R; ++j) {
         maxValue = max(maxValue, (i & j));
      }
   }
   return maxValue;
}
int main() {
   int L = 1, R = 10;
   cout << "Maximum value = " << getMaxBitwiseAndValue(L, R) << endl;
   return 0;
}

输出结果

Maximum value = 8