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

จำนวนคู่ที่ Bitwise OR ให้เลขคี่ใน C++


ให้อาเรย์ หาจำนวนคู่ที่ Bitwise OR ให้ผลลัพธ์เป็นเลขคี่

ตัวอย่าง:

Input: arr = [1, 2]
Output: 1

คู่ (1, 2) ให้ OR เป็น 3 (คี่)

อัลกอริทึม

  • กำหนดอาเรย์
  • count = 0
  • วนลูป 2 ชั้นหาทุกคู่:
    • คำนวณ bitwise OR
    • ถ้าผลลัพธ์ % 2 != 0 count++
  • คืนค่า count

การเขียนโปรแกรม C++

#include <bits/stdc++.h> using namespace std; int getOddPairsCount(int arr[], int n) {    int count = 0;    for (int i = 0; i < n; i++) {       for (int j = i + 1; j < n; j++) {          if ((arr[i] | arr[j]) % 2 != 0) count++;       }    }    return count; } int main() {    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };    int n = 10;    cout << getOddPairsCount(arr, n) << endl;    return 0; }

ผลลัพธ์

35