我们给了一个整数数组,任务是计算使用给定数组值可以形成的对的总数,以便对这些对执行OR操作将导致该值小于给定对中的MAX值。
或运算的真值表如下
一种 | 乙 | AVB |
0 | 0 | 0 |
1个 | 0 | 1个 |
0 | 1个 | 1个 |
1个 | 1个 | 1个 |
输入− int arr [] = {2,5,1,8,9}
输出-按位或小于Max的对数为-3
解释-
X | ÿ | XVY |
2 | 5 | 7> 5 =假 |
2 | 1个 | 3> 2 =假 |
2 | 8 | 10> 8 =假 |
2 | 9 | 11> 9 =假 |
5 | 1个 | 5 = 5是 |
5 | 8 | 13> 8 =假 |
5 | 9 | 13> 9 =假 |
1个 | 8 | 9> 8 =假 |
1个 | 9 | 10> 9 =假 |
8 | 9 | 9 = 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