Separate Numbers - Bit Operations

Time limit: 1000ms Memory limit: 65536K

Given an array  A , all but one number appears three times. Find the number that occurs once.

For example: { 1 , 2 , 1 , 2 , 1 , 2 , 7 } , find  7 .

Your algorithm can only be of linear time complexity and cannot use extra space~

input format

Enter a number  n ( 1 n 5 0 0 ) on the first line , representing the length of the array.

The next line inputs   integers in the range of n ints ( 2 1 4 7 4 8 3 6 4 8 2 1 4 7 4 8 3 6 4 7 ), representing the array  A . The input array is guaranteed to be valid.

output format

Output an integer representing a number that occurs only once in the array.

sample input

4
0 0 0 5

Sample output

5

Summarize:

The correct idea of ​​this question is of course bit operation. From the question, if all the numbers except one number are 3, then the result can be obtained by adding the number by bit and taking the remainder of 3.

E.g:

1: 0 0 0 1 
2: 0 0 1 0 
1: 0 0 0 1 
2: 0 0 1 0 
1: 0 0 0 1 
2: 0 0 1 0 
7: 0 1 1 1 
───────── 
 0 1 4 4

0 1 4 4 Divide each bit by 3 and get the remainder 0 1 1 1 => 7

Code:

#include <iostream>

using namespace std;

int main(){
    int sum[32], N, a;
    for(int i=0; i<32; i++){
        sum[i] = 0;
    }
    cin>>N;
    for(int i=0; i<N; i++){
        cin>>a;
        for(int j=0; j<32; j++){
            sum[j]+=a>>j&1;
            sum[j]%=3;   
        }
    }
    int years = 0;
    for(int i=0; i<32; i++){
        ans += sum[i]<<i;
    }
    cost<<years;
}

In addition, as the saying goes, real masters can solve all problems with violence, although I have never seen such masters, but the requirements of this problem are easier to use violence.

Code:

#include <iostream>
#include <algorithm>

using namespace std;

int board[505];

int main(){
	
	int N;
	cin>>N;
	for(int i=0 ; i<N ; i++){
		cin>>board[i];
	}
	sort(board,board+N);//sort
	for(int i=0 ; i<N ; i++){
		if((i-1<0 || board[i]!=board[i-1]) && (i+1>=N || board[i]!=board[i+1])){
			cout<<board[i];
			break;
		}
	}
	
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325949563&siteId=291194637