閱讀679 返回首頁    go 技術社區[雲棲]


[LeetCode]136.Single Numbe

【題目】

【解析】

在此我們利用異或的一個性質:

任何一個數字異或他自己都等於0。也就是說我們從頭到尾異或數組中的每一個數字,

那麼最終的結果剛好是哪個隻出現一次的數字,因為那些成對出現的數字全部在異或中抵消了。

【代碼】

class Solution {
public:
    int singleNumber(int A[], int n) {
        int i,result = 0;
        if(A == NULL || n <= 0){
            return -1;
        }
        for(i = 0;i < n;i++){
            result ^= A[i];
        }
        return result;
    }
};

/*********************************
*   日期:2013-12-04
*   作者:SJF0115
*   題目: 136.Single Number
*   網址:https://oj.leetcode.com/problems/single-number/
*   結果:AC
*   來源:LeetCode
*   博客:
**********************************/
#include <iostream>
#include <malloc.h>
#include <stdio.h>
using namespace std;

int *array;

int singleNumber(int A[], int n) {
    int i,result = 0;
    if(A == NULL || n <= 0){
        return -1;
    }
    for(i = 0;i < n;i++){
        result ^= A[i];
    }
    return result;
}

int main() {
    int i,n;
    while(scanf("%d",&n) != EOF){
        array = (int*)malloc(sizeof(int)*n);
        for(i = 0;i < n;i++){
            scanf("%d",&array[i]);
        }
        printf("%d\n",singleNumber(array,n));
    }//while
    return 0;
}





最後更新:2017-04-03 14:54:43

  上一篇:go 手機衛士05-自定義對話框
  下一篇:go 最牛B的編碼套路