位運算的兩道題目

 

 

做位運算自己一直出錯,兩道中等的題目代碼反而接近兩個小時.....

位運算的優先級一直沒搞對,有兩點需要注意

1.(Xor& count == 0) 會出錯, 應該寫成(Xor & count) == 0

2.curBit << 1; 會出錯  應該寫成curBit = curBit <<1;

面試題56:數組中數字出現的次數

由於符號優先級那裏搞錯了,(Xor&count) ==0

思路:根據異或結果不爲0,然後利用異或結果爲1進行切割數組。學習

for(auto it:nums){  if(滿足條件) 進桶1

}

https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/

class Solution {
public:
    vector<int> singleNumbers(vector<int>& nums) {
        //  x ^ 0 = x;
        //這個結果就是兩個數的Xor節點,我們用它來分組
        int Xor = 0;
        for(auto it : nums){
            Xor ^= it;
        }
        
        //找到1個1即可,用它來進行分組
        int count = 1;
        while( ( Xor & count) == 0){//這裏需要小心,((Xor^count))一定要加括號
            count <<= 1;
        }

        //這樣的話就得到了count在哪裏
        int num1 = 0;
        int num2 = 0;
        for(auto it:nums){
            if( (it & count) == 0){//我他媽服了,這裏==號優先級比較大,並且必須是==0/count之前merge也是
                num1 = num1 ^ it;
            }else{
                num2 = num2 ^ it;
            }
        }

        vector<int> res;
        res.push_back(num1);
        res.push_back(num2);
        return res;
    }
};

https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-ii-lcof/submissions/

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        //出現了3次的數字,他們那一位相加起來的結果肯定%3=0
        //然後因爲
        //[1 2 2 2]
        int res = 0;
        for(int i = 0 ; i < 32 ; i++){
            int curBit = 1 << i; //這種比較巧妙,最多也就是到達了2^31次
            int count = 0 ;
            for(auto it : nums){
                //對於這一位都進行相加
                 if((it & curBit) !=0) count++;
            }
            if((count%3) !=0) res = res | curBit;
            
        }
        return res;
    }
};

 

過程中也遇到bug,主要說的就是出現了負數左移的情況。

Line 16: Char 28: runtime error: left shift of negative value -2147483648 (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:26:28

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章