首页 > 文章列表 > 查找出现奇数次数的数字的C/C++程序

查找出现奇数次数的数字的C/C++程序

数字 查找 奇数次数
243 2023-09-11

一个C++程序,用于在给定的正整数数组中找到出现奇数次数的数字。在这个数组中,所有数字都出现偶数次。

Input: arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7}
Output: 7

Explanation

使用两个循环,外部循环逐个遍历所有元素,内部循环计算外部循环遍历的元素出现的次数。

Example

#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;
}