leetcode题目:
给定一个包含n个整数的数组,除了一个数出现一次外所有的整数均出现三次,找出这个只出现一次的整数。
使用位运算是最佳的解法。
下面具体解释一下整个代码:对于所有数的各个数位进行统计,每一位为1的出现次数取mod3,即只有出现0,1,2次三种情况。
若该位为1出现一次,则one中该位为1;出现两次,则two中该位为1;出现0次,three中该位为1
即one 保存出现一次的各个数位,two保存出现两次的各个数位。
而出现三次的整数的各个数位在取了mod3后,相当于出现0次;只有出现一次的整数体现在one的各个位上,即等于one的值
结果即one的值。
1.写法一比较绕
int singleNumber(int A[], int n) {
int one = 0, two = 0, three = 0;
for(int i = 0; i< n; ++i){
two |= one&A[i];
one ^= A[i];
three = one&two;
one &= ~three;
two &= ~three;
}
return one;
}
2.写法二明白一些
int singleNumber(int A[], int n) {
int one = 0, two = 0, three = 0;
for(int i = 0; i< n; ++i){
three = ~(one|two);
int add_two = one&A[i];//已经出现1次并且A[i]中也为1的数位
int add_three = two&A[i];//已经出现2次并且A[i]中也为1的数位
int add_one = three&A[i];//已经出现0次并且A[i]中也为1的数位
one = (one^add_two) |add_one;//{已出现1次并且A[i]中不为1的,已出现0次并A[i]中为1的}数位
two = (two^add_three) | add_two;
}
return one;
}