大多数运行时有效的方法来比较两个非常大的数字(大于长)

时间:2017-05-13 16:55:11

标签: java numbers compare biginteger

我想比较两个非常大的数字。

我当前的方法有效,但某些输入需要超过2000毫秒。

我的代码:

import java.io.*;
import java.math.*;
import static java.lang.Math.pow;

public class comparelarge {
    public static void main(String[] args) throws IOException {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader bf = new BufferedReader(isr);
        PrintWriter out = new PrintWriter(System.out);

        String first = bf.readLine();
        String second = bf.readLine();
        BigInteger big1 = new BigInteger(first);
        BigInteger big2 = new BigInteger(second);

        if(big1.compareTo(big2) == 1){
            out.println('>');
            out.flush();
        }
        else if(big1.compareTo(big2) == -1){
            out.println('<');
            out.flush();
        }
        else{
            out.println('=');
            out.flush();
        }
    }
}

请告知我如何在没有过多运行时间的情况下准确比较大数字。

1 个答案:

答案 0 :(得分:2)

1。)你正在做compareTo两次;将结果存储在变量中并重用它。 (与1/-1>0

相比,不要与<0进行比较

Strings上有一些东西/优化,但你需要小心,因为这些可能导致一些数字格式的错误答案。在我看来,最好是安全并坚持BigInteger

2。)如果您只有正数而不是具有0前缀的数字;您可以检查String.length更长的字符串包含更大的数字。

3.。)在相同长度的字符串上,你可以完全绕过BigInteger的String.compareTo()。