// Source : https://oj.leetcode.com/problems/single-number-ii/ // Author : Hao Chen // Date : 2014-06-17 /********************************************************************************** * * Given an array of integers, every element appears three times except for one. Find that single one. * * Note: * Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? * * **********************************************************************************/ class Solution { public: int singleNumber(int A[], int n) { int ones = 0, twos = 0, threes = 0; for (int i = 0; i < n; i++) { twos |= ones & A[i]; ones ^= A[i];// 异或3次 和 异或 1次的结果是一样的 //对于ones 和 twos 把出现了3次的位置设置为0 (取反之后1的位置为0) threes = ones & twos; ones &= ~threes; twos &= ~threes; } return ones; } };