给定n个整数,请统计奇数和偶数各有多少个
时间: 2024-05-09 13:19:35 浏览: 128
算法1:遍历
遍历整个数组,统计奇数和偶数的个数。
时间复杂度:O(n)
C++ 代码
```
#include <iostream>
using namespace std;
int main() {
int n, num, odd = 0, even = 0;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> num;
if (num % 2 == 0) {
even++;
} else {
odd++;
}
}
cout << "Odd: " << odd << endl;
cout << "Even: " << even << endl;
return 0;
}
```
算法2:位运算
奇数二进制的最后一位是1,偶数二进制的最后一位是0。因此可以通过位运算来判断奇偶性。
时间复杂度:O(n)
C++ 代码
```
#include <iostream>
using namespace std;
int main() {
int n, num, odd = 0, even = 0;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> num;
if (num & 1) {
odd++;
} else {
even++;
}
}
cout << "Odd: " << odd << endl;
cout << "Even: " << even << endl;
return 0;
}
```
阅读全文