@@ -33,7 +33,7 @@ class Solution {
3333 *
3434 * Because the same number appear 3 times, which means the sum of i-th bits for all numbers should be 3 times.
3535 *
36- * In other word, the sum of i-th bits mod 3, it must be 0 or 1. 1 means that is the single number bit.
36+ * In other word, the sum of the i-th bits mod 3, it must be 0 or 1. 1 means that is the single number bit.
3737 *
3838 * This solution can be easy to extend to "every element appears k times except for one."
3939 *
@@ -60,10 +60,10 @@ class Solution {
6060 *
6161 * Let's see how it improve the above.
6262 *
63- * We use three bitmask ,
64- * 1) `ones` represent the i-th bit had apear once.
65- * 2) `twos` represent the i-th bit had apear twice.
66- * 3) `threes` represent the i-th bit had apear three times.
63+ * We use three bitmasks ,
64+ * 1) `ones` as a bitmask which represents the i-th bit had appeared once.
65+ * 2) `twos` as a bitmask which represents the i-th bit had appeared twice.
66+ * 3) `threes` as a bit mask which represents the i-th bit had appeared three times.
6767 *
6868 * When the i-th bit had appeared for the third time, clear the i-th bit of both `ones` and `twos` to 0.
6969 * The final answer will be the value of `ones`
@@ -72,9 +72,13 @@ class Solution {
7272 int singleNumber_2 (int A[], int n) {
7373 int ones = 0 , twos = 0 , threes = 0 ;
7474 for (int i = 0 ; i < n; i++) {
75- twos |= ones & A[i];
75+ // `ones & A[i]` the result is the bitmask which the bits appeared twice
76+ twos |= ones & A[i];
77+ // XOR means remove the bit which appeared twice int `ones`
7678 ones ^= A[i];
79+ // count the `three`
7780 threes = ones & twos;
81+ // clear the `ones` and `twos` if the i-th bit had appeared three times.
7882 ones &= ~threes;
7983 twos &= ~threes;
8084 }
0 commit comments