如何在数组中找到3个最大的BigInteger
个对象?这是我现在的代码。
package masivi;
import java.math.BigInteger;
import java.util.Scanner;
public class largest3Numbers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
BigInteger[] numbers = new BigInteger[n];
BigInteger tempbiggest1 = new BigInteger("0");
BigInteger biggest1 = new BigInteger("0");
BigInteger tempbiggest2 = new BigInteger("0");
BigInteger biggest2 = new BigInteger("0");
BigInteger tempbiggest3 = new BigInteger("0");
BigInteger biggest3 = new BigInteger("0");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = scan.nextBigInteger();
if (numbers[i] > tempbiggest1) {
}
}
}
}
答案 0 :(得分:3)
这不会编译:
if (numbers[i] > tempbiggest1) {
您无法在>
个对象上使用BigInteger
运算符。请改用compareTo
:
// Check if numbers[i] is larger than tempbiggest1
if (numbers[i].compareTo(tempbiggest1) > 0) {
答案 1 :(得分:1)
只需使用Array.sort对数组进行排序并获取数组中的最后三个元素:
public class SortBigIntegers {
public static void main(String[] args) {
BigInteger[] numbers = new BigInteger[6];
numbers[0] = new BigInteger("10000000");
numbers[1] = new BigInteger("200000000");
numbers[2] = new BigInteger("30000000");
numbers[3] = new BigInteger("5555555555555");
numbers[4] = new BigInteger("6666666666");
numbers[5] = new BigInteger("0");
Arrays.sort(numbers );
System.out.println("the three biggest are: " + numbers[5] + ", " + numbers[4] + ", " + numbers[3]);
}
}
答案 2 :(得分:0)
当我们使用Arrays.sort时,元素应该是自然可比的,BigInteger是实现可比较的接口。 还有很少的其他方法,比如复制到TreeSet等,但会有更多的空间复杂性。