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:

  1. Include necessary headers: #include <iostream> and #include <vector> are included for input/output operations and using the std::vector container.

  2. 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 formula n * (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.

  3. Main function: The main function demonstrates the usage of the findMissingNumber function with an example vector numbers. It prints the result to the console.

  4. Example usage: In the example, the vector numbers contains integers from 1 to 8 with one missing number (5). The findMissingNumber function is called with this vector, and the missing number is printed to the console.