此题就是对32个位分别数1的个数,如果是3的倍数,那么所求数该位为0,否则该位为1。
public class Solution { public int singleNumber(int[] A) { int ans = 0; for (int i = 0; i < 32; i++) { int cnt = 0; for (int j = 0; j < A.length; j++) { if ((A[j] & (1 << i)) != 0) cnt++; } if (cnt % 3 != 0) ans |= (1 << i); } return ans; } }
第二刷:其实数组不需要,要注意位运算的优先级低
class Solution { public: int singleNumber(int A[], int n) { int bits[32] = {}; for (int i = 0; i < n; i++) { for (int j = 0; j < 32; j++) { int k = (A[i] & (1 << j)) == 0 ? 0 : 1; bits[j] = (bits[j] + k) % 3; } } int r = 0; for (int i = 0; i < 32; i++) { if (bits[i] != 0) { r |= (1 << i); } } return r; } };