开辟一个数组通过 %2 来计算斐波那契数。
代码如下:
import java.math.BigDecimal; import java.math.BigInteger; import java.util.Locale; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); BigInteger[] a = new BigInteger[2]; int num, ca; ca = in.nextInt(); while (ca-- > 0) { a[0] = a[1] = BigInteger.ONE; num = in.nextInt(); for (int i = 3; i <= num; ++i) { a[i % 2] = a[i % 2].add(a[(i - 1) % 2]); } System.out.println(a[num%2]); } } }