Compare big integers in array

限于喜欢 提交于 2019-12-12 02:56:08

问题


How to find 3 the biggest BigInteger objects in array? This is my code for now.

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) {

            }
        }
    }
}

回答1:


This will not compile:

if (numbers[i] > tempbiggest1) {

You cannot use the > operator on BigInteger objects. Use compareTo instead:

// Check if numbers[i] is larger than tempbiggest1
if (numbers[i].compareTo(tempbiggest1) > 0) {



回答2:


Just use Array.sort to sort the array and take the last three elements in the array:

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]);

     }
}



回答3:


  • First sort the array . You can use one of internal Arrays.sort utility.
  • In the sorted array you can fetch the elements like this .. a[len-1] , a[len-2],a[len-3] where len is yourarray.length

When we use Arrays.sort the elements should be naturally comparable and BigInteger is and implements comparable interface. Thre are few other approaches as well like copying into TreeSet etc but will have more space complexcity.



来源:https://stackoverflow.com/questions/30543987/compare-big-integers-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!