Single Number的加強班
有n個數字,除了一個只出現過一次,其他的都出現了3次!
出現兩次我們知道就是xor下就木有啦,那3次怎么搞?
我們還是用二進制位的方式來思考。
那么這些位,除去出現過一次的那個后,其他的都是3的倍數!- -我們把所有位1的個數mod 3,那么剩下的就是只出現過一次那個啦。
我們也沒必要開個啥 int bit[32]的數組去統計的
= =我們來模擬二進制加法
用兩位來計數,到3就把該位清零。
bit2 bit1
bit1 如果該位來的是1 ,保持0,1,0,1。。。(也就是xor),如果是0就不變
當bit1=1的時候再來一個1,那么bit2=1
當這兩個bit同時為1,說明這是3啦(二進制你想想嘛),該位清零。
class Solution { public: int singleNumber(int A[], int n) { // Note: The Solution object is instantiated only once and is reused by each test case. int one = 0; int two = 0; int three = 0; for(int i = 0 ; i < n ; i++){ two |= A[i] & one; one = A[i] ^ one; three = ~(one&two); one &= three; two &= three; } return one; } };