C/C++ 程式用於查詢給定正整數陣列中出現奇數次的數字。此陣列中所有數字都出現偶數次。
此 C++ 程式用於在給定的正整數陣列中查找出現奇數次的數字。此陣列中所有數字都出現偶數次。
Input: arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7}
Output: 7說明
使用兩個迴圈,其中外迴圈逐個遍歷所有元素,內迴圈統計外迴圈遍歷的元素出現的次數。
示例
#include <iostream>
using namespace std;
int Odd(int arr[], int n){
for (int i = 0; i < n; i++) {
int ctr = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j])
ctr++;
}
if (ctr % 2 != 0)
return arr[i];
}
return -1;
}
int main() {
int arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7};
int n = 9;
cout <<Odd(arr, n);
return 0;
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP