查找出現奇數次數數字的 C/C++ 程式?
在這個程式中,我們將看到如何獲取一個數組中出現奇數次的數字。有許多不同的方法。其中一種最簡單的方法是執行 ZOR 操作。如果一個數字與其自身進行 XOR 操作,結果將為 0。因此,如果一個數字與偶數次進行 XOR 操作,結果將為 0,否則將為數字本身。
此解決方案有一個問題,如果有多個元素出現奇數次,它將返回其中一個元素。
演算法
getNumOccurredOdd(arr, n)
begin res := 0 for each element e from arr, do res := res XOR e done return res end
示例
#include <iostream>
using namespace std;
int getNumOccurredOdd(int arr[], int n) {
int res = 0;
for (int i = 0; i < n; i++)
res = res ^ arr[i];
return res;
}
int main() {
int arr[] = {3, 4, 6, 5, 6, 3, 5, 4, 6, 3, 5, 5, 3};
int n = sizeof(arr)/sizeof(arr[0]);
cout << getNumOccurredOdd(arr, n) << " is present odd number of times";
}輸出
6 is present odd number of times
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP