1. 程式人生 > >Lintcode 83. 落單的數 II

Lintcode 83. 落單的數 II

給出3*n + 1 個的數字,除其中一個數字之外其他每個數字均出現三次,找到這個數字

 

public int singleNumberII(int[] A) {
    // write your code here
    //https://blog.csdn.net/ys_sarah/article/details/51025910
    if(A == null || A.length == 0)
        return 0;
    int[] bits = new int[32];
    int result = 0;
    for(int i = 0; i < 32; i++){
        for(int j = 0; j < A.length; j++){
            int t = A[j]>>i;   //不斷地把位移到最後一位和1做並
            int m = t & 1;     //如果是1的話bits[i]就會+1
            bits[i] += m;
        }
        bits[i] = bits[i] % 3;
        result = result | bits[i] << i;
    }
    return result;

//https://blog.csdn.net/ys_sarah/article/details/51025910?utm_source=copy
}

summary:位操作的題真的不會,大致思路就是換個角度思考這個問題,其實異或就是把整數的32位的0,1串當做整數0,1,對應位加和後,對2取餘的結果,那麼對於這樣三個數的情況,一樣的,可以用相同的方法,對應位的0,1相加,最後對3取餘。得到的結果就是那個落單的數的二進位制表示。然後恢復成整數即可。