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?
// Source : https://oj.leetcode.com/problems/single-number-ii/
// Author : Chao Zeng
// Date : 2014-12-20
class Solution
{
public:
int array[32];
void countone(int n)
{
int k = 0;
while (n)
{
array[k++] += n % 2;
n /= 2;
}
}
int singleNumber(int A[], int n)
{
for (int i = 0; i < 32; i++)
array[i] = 0;
int num = 0;
//难点主要在于将负数转为正数然后求二进制数,然后确定所求数的符号
for (int i = 0; i < n; i++){
if (A[i] < 0){
num ++;
A[i] = -A[i];
}
countone (A[i]);
}
for (int i = 0; i < 32; i++)
array[i] %= 3;
int ans = 0;
for (int i = 0; i < 32; i++){
int bonus = 1;
if (array[i])
{
for (int j = 0; j < i ; j++)
bonus = bonus * 2;
}
else
bonus = 0;
ans = bonus + ans;
}
if (num % 3 == 1)
ans = -ans;
return ans;
}
};