Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หาจำนวนคู่ในอาร์เรย์ที่ XOR เท่ากับ 0 ด้วย C++

สมมติว่าเรามีอาร์เรย์ n สมาชิก เราต้องหาจำนวนคู่ในอาร์เรย์ที่ XOR จะเป็น 0 คู่ (x, y) ที่ XOR เป็น 0 แล้ว x = y เพื่อแก้ปัญหานี้ เราสามารถจัดเรียงอาร์เรย์ แล้วถ้าสมาชิกสองตัวติดกันเท่ากัน ให้เพิ่มตัวนับ ถ้าสมาชิกทั้งหมดเท่ากัน ตัวนับตัวสุดท้ายอาจไม่นับ ในกรณีนั้น เราจะตรวจสอบว่าสมาชิกสุดท้ายและตัวแรกเท่ากันหรือไม่ ถ้าเท่ากัน ให้เพิ่มตัวนับอีก 1

ตัวอย่างโค้ด

#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);
}

ผลลัพธ์

Number of pairs: 2