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

更新于: 20-Aug-2019

350 次浏览

开启你的 事业

完成课程即可获得认证

开始
广告
© . All rights reserved.