LoginSignup
0
0

More than 3 years have passed since last update.

【アルゴリズム】Xだけ間隔がのあるN個の数字

Last updated at Posted at 2020-08-01

問題説明

メソッドsolutionは整数xと自然数nのパラメータを受け取り、xから初めてxずつ増加する数字をn個もつリストをリターンします。
次の条件を見ていただき、条件を満足させるメソッドsolutionを作成してください。

条件

  • xは-10000000以上、10000000以下の整数である。
  • nは1000以下の自然数である。

入出力の例

x n result
2 5 [2,4,6,7,10]
4 3 [4,8,12]
-4 2 [-4,-8]

解説

※解説は私が作成したコードなので、もっといいアルゴリズム等々ありましたら、共有してください!


class Solution {
    public long[] solution(int x, int n) {
        long[] result = new long[n];
        result[0] = x; // xから初めるので、Index 0にxを初期化

        // 上記で0番は初期化したので、iは1からスタートし、nまで繰り返し
        for (int i = 1; i < n; i++) {
            // xずつ増加していくので、resultのIndex:i - 1の値 + xを行う。
            result[i] = result[i - 1] + x;
        }

        return result;
    }
}
0
0
1

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
0
0