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
Minimum XOR Value Pair in C++
Problem statement
Given an array of integers. Find the pair in an array which has minimum XOR value
Example
If arr[] = {10, 20, 30, 40} then minimum value pair will be 20
and 30 as (20 ^ 30) = 10.
(10 ^ 20) = 30
(10 ^ 30) = 20
(10 ^ 40) = 34
(20 ^ 30) = 10
(20 ^ 40) = 60
(30 ^ 40) = 54
Algorithm
- Generate all pairs of given array and compute XOR their values
- Return minimum XOR value
Example
#include <bits/stdc++.h>
using namespace std;
int getMinValue(int *arr, int n) {
int minValue = INT_MAX;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
minValue = min(minValue, arr[i] ^ arr[j]);
}
}
return minValue;
}
int main() {
int arr[] = {10, 20, 30, 40};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Minimum value = " << getMinValue(arr, n) << endl;
return 0;
}
When you compile and execute above program. It generates following output −
Output
Minimum value = 10
Advertisements