
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Count all pairs of an array which differ in K bits in C++
In this tutorial, we will be discussing a program to find the number of pairs of an array which differ in K bits.
For this we will be provided with an array and an integer K. Our task is to find the number of pairs who differ by K bits in their binary representation.
Example
#include <bits/stdc++.h> using namespace std; //counting number of bits in //binary representation int count_bit(int n){ int count = 0; while (n) { if (n & 1) ++count; n >>= 1; } return count; } //counting the number of pairs long long count_pair(int arr[], int n, int k) { long long ans = 0; for (int i = 0; i < n-1; ++i) { for (int j = i + 1; j < n; ++j) { int xoredNum = arr[i] ^ arr[j]; if (k == count_bit(xoredNum)) ++ans; } } return ans; } int main() { int k = 2; int arr[] = {2, 4, 1, 3, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Total pairs for k = " << k << " are " << count_pair(arr, n, k) << "\n"; return 0; }
Output
5
- Related Questions & Answers
- K-diff Pairs in an Array in C++
- Count pairs in an array such that both elements has equal set bits in C++
- Count divisible pairs in an array in C++
- Count all distinct pairs with difference equal to k in C++
- Count the number of elements in an array which are divisible by k in C++
- K Inverse Pairs Array in C++
- Sum of XOR of all pairs in an array in C++
- XOR of all elements of array with set bits equal to K in C++
- Sort an array according to count of set bits in C++
- Count pairs in array whose sum is divisible by K in C++
- Find the maximum cost of an array of pairs choosing at most K pairs in C++
- Find all pairs (a, b) in an array such that a % b = k in C++
- Count of index pairs with equal elements in an array in C++
- Sum of XOR of sum of all pairs in an array in C++
- C++ program to count number of pairs for which product is an integer
Advertisements