📌  相关文章
📜  按位 XOR 值大于其按位 AND 值的对的计数

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

按位 XOR 值大于其按位 AND 值的对的计数

给定一个包含N个正整数的数组arr 。查找按位XOR值大于按位AND值的所有可能对的计数

例子

方法:参考下面的思路来解决这个问题:

请按照以下步骤解决此问题:

  • 检查每一对按位异或值是否大于按位与。
  • 如果是,则增加计数
  • 返回计数。

以下是上述方法的实现:

C++
// C++ program to Count number of pairs
// whose bit wise XOR value is greater
// than bit wise AND value
 
#include 
using namespace std;
 
// Function that return count of pairs
// whose bitwise xor >= bitwise
long long valid_pairs(int arr[], int N)
{
    long long cnt = 0;
    // check for all possible pairs
    for (int i = 0; i < N; i++) {
        for (int j = i + 1; j < N; j++) {
            if ((arr[i] ^ arr[j]) >= (arr[i] & arr[j]))
                cnt++;
        }
    }
 
    return cnt;
}
 
// Driver Code
int main()
{
    int N = 3;
    int arr[] = { 12, 4, 15 };
    cout << valid_pairs(arr, N);
}


Java
// Java program to Count number of pairs
// whose bit wise XOR value is greater
// than bit wise AND value
import java.io.*;
 
class GFG
{
 
  // Function that return count of pairs
  // whose bitwise xor >= bitwise
  public static long valid_pairs(int arr[], int N)
  {
    long cnt = 0;
 
    // check for all possible pairs
    for (int i = 0; i < N; i++) {
      for (int j = i + 1; j < N; j++) {
        if ((arr[i] ^ arr[j]) >= (arr[i] & arr[j]))
          cnt++;
      }
    }
 
    return cnt;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int N = 3;
    int arr[] = { 12, 4, 15 };
    System.out.print(valid_pairs(arr, N));
  }
}
 
// This code is contributed by Rohit Pradhan.


Python3
# python3 program to Count number of pairs
# whose bit wise XOR value is greater
# than bit wise AND value
 
# Function that return count of pairs
# whose bitwise xor >= bitwise
def valid_pairs(arr, N):
 
    cnt = 0
     
    # check for all possible pairs
    for i in range(0, N):
        for j in range(i + 1, N):
            if ((arr[i] ^ arr[j]) >= (arr[i] & arr[j])):
                cnt += 1
 
    return cnt
 
# Driver Code
if __name__ == "__main__":
 
    N = 3
    arr = [12, 4, 15]
    print(valid_pairs(arr, N))
 
    # This code is contributed by rakeshsahni


Javascript


输出
2

时间复杂度:O(N*N)
辅助空间:O(1)