
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum Bitwise AND Value of a Pair in an Array in C++
Problem statement
Given an array of n positive elements. we need to find the maximum bitwise AND value generated by any pair of element from the array.
Example
If input array is {10, 12, 15, 18} then maximum value of bitwise AND is 12.
Algorithm
The result of bitwise AND operations on single bit is maximum when both bits are 1. Considering this property −
- Start from the MSB and check whether we have minimum of two elements of array having set value
- If yes, then that MSB will be part of our solution and be added to result otherwise we will discard that bit
- Similarly, iterating from MSB to LSB (32 to 1) for bit position we can easily check which bit will be part of our solution and will keep adding all such bits to our solution
Example
Let us now see an example −
#include <bits/stdc++.h> using namespace std; int checkBits(int *arr, int n, int pattern) { int cnt = 0; for (int i = 0; i < n; ++i) { if ((pattern & arr[i]) == pattern) { ++cnt; } } return cnt; } int getMaxBitwiseAnd(int *arr, int n) { int result = 0; int count; for (int i = 31; i >= 0; --i) { count = checkBits(arr, n, result | (1 << i)); if (count >= 2) { result |= (1 << i); } } return result; } int main() { int arr[] = {10, 12, 15, 18}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum bitwise AND = " << getMaxBitwiseAnd(arr, n) << endl; return 0; }
Output
Maximum bitwise AND = 12
Advertisements