C++ 中总和为 2 的幂的对数
在本教程中,我们将编写一个程序来计算总和为2的幂的对数。
让我们看看解决问题的步骤。
编写两个循环以获取数组的所有对。
计算每对的总和。
使用按位与检查总和是否为2的幂。
如果计数是2的幂,则增加计数。
示例
让我们看看代码。
#include输出结果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
结论
如果您对本教程有任何疑问,请在评论部分提及。