Đề bài
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.
Ràng buộc
0 ≤ length ≤ 100,000; the total fits in a 64-bit integer
Ví dụ
Đầu vào:
numbers = [1, 2, 3, 4]
Kết quả mong đợi:
expected = 10
Đầu vào:
std::vector<long long> numbers = {1, 2, 3, 4};
Kết quả mong đợi:
long long expected = 10;
Đầu vào:
long[] numbers = new long[] {1, 2, 3, 4};
Kết quả mong đợi:
long expected = 10;
Giải thích
1 + 2 + 3 + 4 = 10.
Đầu vào:
numbers = []
Kết quả mong đợi:
expected = 0
Đầu vào:
std::vector<long long> numbers = {};
Kết quả mong đợi:
long long expected = 0;
Đầu vào:
long[] numbers = new long[] {};
Kết quả mong đợi:
long expected = 0;
Giải thích
Nothing to add: 0.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Add every element as you traverse the list once.
Gợi ý 2
Keep a running total instead of building anything extra.
Gợi ý 3
An empty list should stay at 0, so the initial total matters.
Độ phức tạp mong đợi
O(n) time, O(1) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.