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

จำนวนคู่ที่ผลรวมเป็นกำลังของ 2 ใน C++


ให้อาเรย์ หาจำนวนคู่ที่ผลรวมเป็นกำลังของ 2 (power of 2)

ตัวอย่าง:

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

คู่ (1, 3) ให้ผลรวม 4 = 2²

อัลกอริทึม

  • กำหนดอาเรย์
  • count = 0
  • วนลูป 2 ชั้นหาทุกคู่:
    • sum = arr[i] + arr[j]
    • เช็ค power of 2: (sum & (sum - 1)) == 0
    • ถ้าเป็น count++
  • คืนค่า count

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

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

ผลลัพธ์

6