Find the Missing Number
#include <iostream>
#include <vector>
int findMissingNumber(const std::vector<int>& nums) {
int n = nums.size() + 1;
int sum = n * (n + 1) / 2;
for (int num : nums) {
sum -= num;
}
return sum;
}
int main() {
// Example usage
std::vector<int> numbers = {1, 2, 4, 6, 3, 7, 8};
int missingNumber = findMissingNumber(numbers);
std::cout << "The missing number is: " << missingNumber << std::endl;
return 0;
}
Explanation:
Include necessary headers:
#include <iostream>
and#include <vector>
are included for input/output operations and using thestd::vector
container.Function to find the missing number: The
findMissingNumber
function takes a vector of integers (nums
) as input and returns the missing number. It calculates the expected sum of numbers from 1 to n using the formulan * (n + 1) / 2
, where n is the size of the input vector plus 1. Then, it subtracts each element in the input vector from the expected sum.Main function: The
main
function demonstrates the usage of thefindMissingNumber
function with an example vectornumbers
. It prints the result to the console.Example usage: In the example, the vector
numbers
contains integers from 1 to 8 with one missing number (5). ThefindMissingNumber
function is called with this vector, and the missing number is printed to the console.