Условие
Return the total of all numbers in the list. An empty list sums to 0.
Implement sum_array(numbers).
Input
numbers: The list of integers.
Output
Return the sum.
Ограничения
0 ≤ length ≤ 100,000; the total fits in a 64-bit integer
Примеры
Ввод:
numbers = [1, 2, 3, 4]
Ожидаемый вывод:
expected = 10
Ввод:
std::vector<long long> numbers = {1, 2, 3, 4};
Ожидаемый вывод:
long long expected = 10;
Ввод:
long[] numbers = new long[] {1, 2, 3, 4};
Ожидаемый вывод:
long expected = 10;
Пояснение
1 + 2 + 3 + 4 = 10.
Ввод:
numbers = []
Ожидаемый вывод:
expected = 0
Ввод:
std::vector<long long> numbers = {};
Ожидаемый вывод:
long long expected = 0;
Ввод:
long[] numbers = new long[] {};
Ожидаемый вывод:
long expected = 0;
Пояснение
Nothing to add: 0.
Как подступиться
Сначала попробуйте сами, затем открывайте подсказки по одной.
Подсказка 1
Add every element as you traverse the list once.
Подсказка 2
Keep a running total instead of building anything extra.
Подсказка 3
An empty list should stay at 0, so the initial total matters.
Ожидаемая сложность
O(n) time, O(1) extra space
Ссылки
Это задание адаптировано для CodeUtility. Следуйте условию и ограничениям выше.