137. Single Number II
3/20/2018 update:
这道题另外一种解法真是太难了。看不懂,性价比超低。
Analysis:
Use array [14,14,14,9] as an example. Translate every number to binary, we can get:
这道题另外一种解法真是太难了。看不懂,性价比超低。
Analysis:
Use array [14,14,14,9] as an example. Translate every number to binary, we can get:
1110
1110
1110
1001
-------
4331 and sum up each position, we can get the result binary from %3 on each position.
Solution:
class Solution {
public int singleNumber(int[] nums) {
int[] A = new int[32];
int result = 0;
for(int i = 0; i < 32; i++)
{
int count = 0;
for(int j = 0; j < nums.length; j++) {
// count nums[j] at position A[i]
if(((nums[j] >> i) & 1) == 1) {
count++;
}
}
if(count > 0) {
result |= (count%3) << i;
}
}
return result;
}
}
评论
发表评论