1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

今日も条件分岐がテーマの問題で、「終了判定」を解いた!問題文に “Σ” が出てきてびっくりしたけど、やることはシンプル!



問題概要

  • 長さ N の数列Aが与えれらる。
  • 数列の中で最初に出てくる奇数の手前までの合計を出す。

入力例:

5
2 4 6 8 1

出力例1:

20



✅OKコード例:

const rl = require('readline').createInterface({ input: process.stdin });
const lines = [];

rl.on('line', (input) => {
    lines.push(input);
});



rl.on('close', () => {
    const N = Number(lines[0]); // 数列の長さ
    const arrA = lines[1].split(' ').map(Number); 



    let even = []; // 最初の奇数までの偶数を格納する配列

    for (let i = 0; i < N; i++) {

        if (arrA[i] % 2 !== 0) {
            break; // 奇数が出たらループ終了
        } 
        
        else {
            even.push(arrA[i]); // 偶数なら追加
        }
    }


    // 偶数たちの合計を計算
    const result = even.reduce((sum, element) => sum + element, 0);
    
    console.log(result); // 結果を出力

});
  • A[i] % 2 !== 0:奇数かどうかのチェック。
  • break:最初の奇数が出た時点でそれ以降は無視。
  • reduce を使ってその合計を計算。



✨ さらにスッキリ書くなら?

    let sum = 0;
    for (let i = 0; i < A.length; i++) {
        
        // 奇数が出たらループ終了
        if (A[i] % 2 !== 0) break; 
        
        // 偶数なら加算
        sum += A[i]; 
    }

    console.log(sum);



💡メモ

  • 奇数チェックは % 2 !== 0
  • break → for 文を終了
  • reduce() で合計を出すとき、初期値0を忘れずに




僕の失敗談(´;ω;`)と解決法🐈

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?