Problème
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.
Contraintes
0 ≤ length ≤ 100,000; the total fits in a 64-bit integer
Exemples
Entrée :
numbers = [1, 2, 3, 4]
Sortie attendue :
expected = 10
Entrée :
std::vector<long long> numbers = {1, 2, 3, 4};
Sortie attendue :
long long expected = 10;
Entrée :
long[] numbers = new long[] {1, 2, 3, 4};
Sortie attendue :
long expected = 10;
Explication
1 + 2 + 3 + 4 = 10.
Entrée :
numbers = []
Sortie attendue :
expected = 0
Entrée :
std::vector<long long> numbers = {};
Sortie attendue :
long long expected = 0;
Entrée :
long[] numbers = new long[] {};
Sortie attendue :
long expected = 0;
Explication
Nothing to add: 0.
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
Add every element as you traverse the list once.
Indice 2
Keep a running total instead of building anything extra.
Indice 3
An empty list should stay at 0, so the initial total matters.
Complexité attendue
O(n) time, O(1) extra space
Références
Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.