C++ 中按位或運算結果為奇數的數對數
給定一個數組,我們必須找出按位或運算結果為奇數的數對。讓我們來看一個示例。
輸入
arr = [1, 2]
輸出
1
只有唯一一對的按位或運算結果為奇數。這對數為 (1, 2)。
演算法
- 用隨機數初始化陣列。
- 將計數初始化為 0。
- 寫兩個迴圈來獲取陣列的數對。
- 計算每對數之間的按位或運算。
- 如果結果為奇數,則增加計數。
- 返回計數。
實現
以下是在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP