计算C ++中按位或小于Max的对

我们给了一个整数数组,任务是计算使用给定数组值可以形成的对的总数,以便对这些对执行OR操作将导致该值小于给定对中的MAX值。

或运算的真值表如下

一种AVB
000
1个01个
01个1个
1个1个1个

输入− int arr [] = {2,5,1,8,9}

输出-按位或小于Max的对数为-3

解释-

XÿXVY
257> 5 =假
21个3> 2 =假
2810> 8 =假
2911> 9 =假
51个5 = 5是
5813> 8 =假
5913> 9 =假
1个89> 8 =假
1个910> 9 =假
899 = 9 = TRUE

以下程序中使用的方法如下

  • 输入整数元素数组以形成一对

  • 计算数组的大小,将数据传递给函数以进行进一步处理

  • 创建一个临时变量计数,以存储通过“或”运算形成的对,其中对的值小于或等于MAX值

  • 从i到0开始循环直到数组的大小为1

  • 在循环内部,从j到i + 1开始另一个循环,直到数组大小

  • 在循环内部,检查IF arr [i] | arr [j] <= max(arr [i],arr [j])然后将计数加1

  • 返回计数

  • 打印结果。

示例

#include <bits/stdc++.h>
using namespace std;
//Count pairs with bitwise OR less than Max
int Pair_OR(int arr[], int size){
   int count = 0;
   for (int i = 0; i lt; size - 1; i++){
      for (int j = i + 1; j lt; size; j++){
         if ((arr[i] | arr[j]) lt;= max(arr[i], arr[j])){
            count++;
         }
      }
   }
   return count;
}
int main(){
   int arr[] = { 4, 8, 9, 10, 23};
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Count of pairs with bitwise OR less than Max are: "<<Pair_OR(arr, size);
   return 0;
}

输出结果

如果我们运行上面的代码,它将生成以下输出-

Count of pairs with bitwise OR less than Max are − 3