JAVA 系列循环

JAVA Loops for a series

我只收到一个测试用例的错误。

问题link:https://www.hackerrank.com/challenges/java-loops/problem?isFullScreen=true JAVA Hacker rank loop question

Sample Input

2
0 2 10
5 3 5
Sample Output

2 6 14 30 62 126 254 510 1022 2046
8 14 26 50 98

我得到准确的输出,但测试用例失败了。

Java中的代码:

import java.util.*;
import java.io.*;

class Solution{
    public static void main(String []argh){
        Scanner sc = new Scanner(System.in);
        
        int q = sc.nextInt();
        if (q==1){
        int a = sc.nextInt();

             System.out.println();

            
        }else{

        int a = sc.nextInt();
        int b = sc.nextInt();
        int n = sc.nextInt();
        
        int sum, x ;
        sum = a;
        

        for (int i=0 ; i<n ; i++){
            x = (int) (Math.pow(2,i)*b);
            sum = sum + x ;

            System.out.print(sum+" ");
        }
        }
            
    }
}

这是我想出的解决方案。它需要对输出进行一些更改,这很简单。

    public static List<Integer> generateSequence(int a, int b, int n) {
    List<Integer> list = new ArrayList<Integer>();
    int currentValue = 0;
    for (int i = 0; i < n; i++) {
        int value = (int) Math.pow(2, i) * b;
        if (i == 0) {
            value += a;
        }
        currentValue += value;
        list.add(currentValue);
    }

    return list;
}

public static void main(String[] args) throws IOException {
    List<List<Integer>> lists = new ArrayList<>();
    try (Scanner scanner = new Scanner(System.in)) {
        int q = scanner.nextInt();
        for (int i = 0; i < q; i++) {
            int a = scanner.nextInt();
            int b = scanner.nextInt();
            int n = scanner.nextInt();              
            lists.add(generateSequence(a, b, n));
        }
    }
    
    for (List<Integer> list : lists) {
        System.out.println(list);
    }
}