編程實戰の異或的應用

題目

輸入N,接下來有2*n-1個數,其中只有1個數只出現一次,其餘均出現2次,編寫函數找出這個數
樣例輸入:

5 
1 2 3 4 5 1 2 3 5

樣例輸出:

4

解:

AC代碼:

#include<iostream>
#include<cstdio>
#include<string>
#include<fstream>
#include<cmath>
#include<cstring>
using namespace std;
int  fun(int n,int a[])
{

  /**********Program**********/
    int res=0;
    for(int i=0;i<2*n-1;i++)
        {
            res^=a[i];
        }
        return res;
  /**********  End  **********/
}

main()
{
    int result;
    int n,a[100];
    cin>>n;
    for (int i=0;i<2*n-1;++i)
    cin>>a[i];
    result=fun(n,a);
    cout<<result<<endl;
}

小結:

  • 任何數異或0值不變,任何數與自己異或值爲0
  • 異或運算有交換律
  • 異或運算是位運算
發佈了36 篇原創文章 · 獲贊 21 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章