-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path268.cpp
More file actions
49 lines (36 loc) · 892 Bytes
/
268.cpp
File metadata and controls
49 lines (36 loc) · 892 Bytes
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
/*
* Written by Nitin Kumar Maharana
* nitin.maharana@gmail.com
*/
//Using XOR.
class Solution {
public:
int missingNumber(vector<int>& nums) {
int result = 0;
for(int i = 1; i <= nums.size(); i++)
result ^= (i ^ nums[i-1]);
return result;
}
};
//Using Summation.
class Solution {
public:
int missingNumber(vector<int>& nums) {
int len = nums.size();
int wholeSum = (len * (len + 1)) / 2;
int arraySum = 0;
for(int i : nums)
arraySum += i;
return wholeSum - arraySum;
}
};
//Using Summation. Optimized
class Solution {
public:
int missingNumber(vector<int>& nums) {
int result = 0;
for(int i = 1; i <= nums.size(); i++)
result += (i-nums[i-1]);
return result;
}
};