C++中陣列所有元素的異或運算(集合位數等於K)
在這個問題中,我們給定一個包含n個元素的陣列和一個整數值k。我們的任務是找到所有集合位數等於k的陣列元素的異或值。
讓我們來看一個例子來理解這個問題:
輸入
array = {2, 12, 44, 103, 17} , K =3輸出
44
為了解決這個問題,我們將計算陣列中每個元素的集合位數,並將其與k進行比較。如果集合位數等於k,則將其推入向量,並找到向量中所有元素的異或值。
為了查詢集合位數,我們將使用`__builtin_popcount()`,這是C++中的一個內建函式。
展示我們解決方案實現的程式:
示例
#include <bits/stdc++.h>
using namespace std;
int XorKSetBits(int arr[], int n, int k){
vector<int> kBitElments;
for (int i = 0; i < n; i++) {
if (__builtin_popcount(arr[i]) == k) {
kBitElments.push_back(arr[i]);
}
}
int result = kBitElments[0];
for (int i = 1; i < kBitElments.size(); i++)
result ^= kBitElments[i];
return result;
}
int main(){
int arr[] = { 2, 12, 44, 103, 17 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
cout<<"XOR of all element of the array with "<<k<<" set bits is : "<<XorKSetBits(arr, n, k);
return 0;
}輸出
XOR of all element of the array with 3 set bits is : 44
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP