C++中求和為2的冪的數對個數


給定一個數組,我們必須找到和為2的冪的數對的個數。讓我們來看一個例子。

輸入

arr = [1, 2, 3]

輸出

1

只有一對數的和是2的冪。這對數是(1, 3)。

演算法

  • 用隨機數初始化陣列。
  • 將計數初始化為0。
  • 編寫兩個迴圈以獲取陣列的所有對。
    • 計算每一對的和。
    • 使用按位與運算子檢查和是否為2的冪。
    • 如果計數是2的冪,則遞增計數。
  • 返回計數。

實現

以下是上述演算法在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

更新於:2021年10月26日

821 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.