起初觉得这道题没什么难度,不就是一个for循环的问题吗,结果还是太年轻了,一提交代码直接错一半的测试用例。。。
之后一看n的取值范围,发现了问题的所在之处,于是我就立马想到了使用BigInteger,我就只是在原有的方法改写成了BigInteger的写法,结果又出现运行超时,和内存超限的错误。
最后直接用了数学中的求和公式 y =(1+x)x/2才做出来
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BigInteger n = scanner.nextBigInteger();
BigInteger sum = BigInteger.ONE;
sum = (BigInteger.ONE.add(n)).multiply(n).divide(BigInteger.valueOf(2));
System.out.println(sum);
}
}
这道题主要是学习一下BigInteger的用法,不能直接把BigInteger改成int,像int型数据一样使用,比如加,减,乘,除,取余,取模,取绝对值,>,=,<等都变成了它特有的方法,详细的BigInteger使用和学习建议直接看这篇博客
Java中BigInteger类的使用方法详解,常用最全系列!
还有一个BigInteger的for循环表达方式:
for (BigInteger i = BigInteger.ZERO; i.compareTo(BigInteger.valueOf(100)) < 0;
i = i.add(BigInteger.ONE))
{
// do your work
}
https://zhidao.baidu.com/question/405910331.html