簡単 0件解決済み 正答率0%

Sum an Array

Add up all values in a list.

このチャレンジで学べること

  • Loop over every element of a list
  • Keep a running total
  • Handle an empty list

問題

翻訳を表示

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

例

例 1
入力:
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.

例 2
入力:
numbers = []

期待される出力:
expected = 0
入力:
std::vector<long long> numbers = {};

期待される出力:
long long expected = 0;
入力:
long[] numbers = new long[] {};

期待される出力:
long expected = 0;

解説

Nothing to add: 0.

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 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用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。