📜  计算按位或小于 Max 的对

📅  最后修改于: 2022-05-13 01:57:47.343000             🧑  作者: Mango

计算按位或小于 Max 的对

给定一个包含N个整数的数组arr[] ,任务是计算索引对(i, j)使得0 ≤ i < j ≤ Narr[i] | arr[j] ≤ max(arr[i], arr[j])其中|是按位或。
例子:

方法:运行两个嵌套循环并检查每个可能的对。如果arr[i] | arr[j] <= max(arr[i], arr[j])然后增加计数。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the count of valid pairs
int countPairs(int arr[], int n)
{
    int cnt = 0;
 
    // Check all possible pairs
    for (int i = 0; i < n - 1; i++)
        for (int j = i + 1; j < n; j++)
            if ((arr[i] | arr[j]) <= max(arr[i], arr[j]))
                cnt++;
 
    return cnt;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countPairs(arr, n);
 
    return 0;
}


Java
// Java implementation of the approach
 
class GFG
{
     
// Function to return the count of valid pairs
static int countPairs(int arr[], int n)
{
    int cnt = 0;
 
    // Check all possible pairs
    for (int i = 0; i < n - 1; i++)
        for (int j = i + 1; j < n; j++)
            if ((arr[i] | arr[j]) <= Math.max(arr[i], arr[j]))
                cnt++;
 
    return cnt;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 3 };
    int n = arr.length;
    System.out.println(countPairs(arr, n));
}
}
 
// This code is Contributed by Code_Mech.


Python3
# Python 3 implementation of the approach
 
# Function to return the count
# of valid pairs
def countPairs(arr, n):
    cnt = 0
 
    # Check all possible pairs
    for i in range(n - 1):
        for j in range(i + 1, n, 1):
            if ((arr[i] | arr[j]) <= max(arr[i],
                                         arr[j])):
                cnt += 1
 
    return cnt
 
# Driver code
if __name__ == '__main__':
    arr = [1, 2, 3]
    n = len(arr)
    print(countPairs(arr, n))
     
# This code is contributed by
# Surendra_Gangwar


C#
// C# implementation of the approach
using System;
 
class GFG
{
     
// Function to return the count of valid pairs
static int countPairs(int []arr, int n)
{
    int cnt = 0;
 
    // Check all possible pairs
    for (int i = 0; i < n - 1; i++)
        for (int j = i + 1; j < n; j++)
            if ((arr[i] | arr[j]) <= Math.Max(arr[i], arr[j]))
                cnt++;
 
    return cnt;
}
 
// Driver code
static void Main()
{
    int []arr = { 1, 2, 3 };
    int n = arr.Length;
    Console.WriteLine(countPairs(arr, n));
}
}
 
// This code is Contributed by mits.


PHP


Javascript


输出:
2