您的位置:首页 > 编程语言 > Go语言

Single Number II

2014-01-28 01:03 411 查看


Single Number II

 Total Accepted: 7073 Total
Submissions: 22573My Submissions

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?
取得每一位的加总和,然后 mod 3, 如果==0, 那么该位一定为0(表示那个数在该位为0),否则该位为1 (那个数如果出现两次,那么取模后是2,如果出现一次,取模后是1)

public static int singleNumber(int[] A) {
int bit = 0;
for (int i = 0; i < 32; i++) {
int sum = 0;
for (int j = 0; j < A.length; j++) {
sum += (A[j] & (1 << i)) >> i;
}
bit |= (sum % 3 == 0 ? 0 : 1) << i; // in this case, the one can appear either once or twice.
}
return bit;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm leetcode