
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
Find Number of Pairs in Array with XOR 0 Using C++
Suppose we have an array of n elements; we have to find a number of pairs in the array whose XOR will be 0. The pair (x, y) whose XOR is 0, then x = y. To solve it we can sort the array, then if two consecutive elements are the same, increase the count. If all elements are the same, then the last count may not be counted. In that case, we will check whether the last and first elements are the same or not, if the same, then increase the count by 1.
Example
#include<iostream> #include<algorithm> using namespace std; int countPairs(int arr[], int n) { int count = 0; sort(arr, arr+n); for(int i = 0; i<n - 1; i++){ if(arr[i] == arr[i+1]){ count++; } } if(arr[0] == arr[n-1]) count++; return count; } int main() { int arr[] = {1, 2, 1, 2, 4}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Number of pairs: " << countPairs(arr, n); }
Output
Number of pairs: 2
Advertisements