-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lonely Integer.cpp
107 lines (69 loc) · 1.68 KB
/
Lonely Integer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
Task: You will be given an array of integers. All of the integers except one occur twice. That one is unique in the array.
Given an array of integers, find and print the unique element.
For example, a=[1,2,3,4,3,2,1], the unique element is 4.
Function Description
Complete the lonelyinteger function in the editor below. It should return the integer which occurs only once in the input array.
lonelyinteger has the following parameter(s):
a: an array of integers
Input Format
The first line contains a single integer, n, denoting the number of integers in the array.
The second line contains n space-separated integers describing the values in a.
Constraints
1<=n<100
It is guaranteed that n is an odd number and that there is one unique element.
0<=a[i]<=100, where 0<=i<n.
Output Format
Print the unique integer in the array.
Sample Input 0
1
1
Sample Output 0
1
Explanation 0
There is only one element in the array, thus it is unique.
Sample Input 1
3
1 1 2
Sample Output 1
2
Explanation 1
We have two 1's, and 2 is unique.
Sample Input 2
5
0 0 1 2 1
Sample Output 2
2
Solution:
#include <iostream>
#include <vector>
using namespace std;
int SingleNumber(vector<int> &ar,int n){
vector<int> f(32,0);
for(int e: ar){
for(int i=0;i<32;i++){
if(e & (1<<i)){
f.at(i)++;
}
}
}
int res =0;
for(int i=0;i<32;i++){
if(f.at(i)%2!=0){
res+=(1<<i);
}
}
return res;
}
int main(){
int n;
cin>>n;
vector<int> v;
for(int i=0;i<n;i++){
int a;
cin>>a;
v.push_back(a);
}
int result = SingleNumber(v,n);
cout<<result;
return 0;
}