-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem63.cpp
More file actions
68 lines (59 loc) · 1.66 KB
/
problem63.cpp
File metadata and controls
68 lines (59 loc) · 1.66 KB
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
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
class ParadeBadge {
public:
vector<int> badges;
// Read badge numbers space-separated
void readInput() {
cout << "Enter badge numbers: ";
int badge;
while (cin >> badge) {
badges.push_back(badge);
if (cin.peek() == '\n') break;
}
}
// Validate input: numbers should be in [0, n-1] and must be unique
bool isValidInput() {
unordered_set<int> seen;
int n = badges.size() + 1; // Because one badge is missing
for (int badge : badges) {
if (badge < 0 || badge >= n) {
cout << "!! Invalid badge number: " << badge << endl;
return false;
}
if (seen.count(badge)) {
cout << "!! Duplicate badge number found: " << badge << endl;
return false;
}
seen.insert(badge);
}
return true;
}
// Find the missing badge number
int findMissing() {
int n = badges.size() + 1; // Total people = n
long long expectedSum = 1LL * (n - 1) * n / 2;
long long actualSum = 0;
for (int badge : badges) {
actualSum += badge;
}
return expectedSum - actualSum;
}
// Print the result
void print(int missing) {
cout << "The missing badge number is: " << missing << endl;
}
};
int main() {
ParadeBadge pb;
pb.readInput();
if (!pb.isValidInput()) {
cout << "!! Invalid Input !!" << endl;
return 1;
}
int missing = pb.findMissing();
pb.print(missing);
return 0;
}