1. 程式人生 > >找出數組中只出現1次的數

找出數組中只出現1次的數

ret ++ [] return 等於 for void 中一 sys

任何數字異或自己都等於0,兩次重復的數字異或之後抵消,最後剩下只有1個的數字
知識點:任何數字異或0等於自身
按位與 a&b 只有雙方為1 才為1
按位或 | 其中一方有1 才為1
按位異或 ^ 雙方相同 為0 不同為 1
註意:本方法只適合於其他數字都出現偶次數才能用

public class Test_plus {
    public static int findNotDouble(int[] a) {
        int n=a.length;
        int result=a[0];
        int i;
        for(i=1;i<n;++i)
            result ^= a[i];
        return result;
    }
    public static void main(String[] args) {
        int array[]= {1,2,3,2,4,3,5,4,1};
        int num = findNotDouble(array);
        System.out.println(num);
    }

}

找出數組中只出現1次的數