在spoj中快速乘法中的TLE

时间:2014-01-02 12:33:02

标签: java

如何更快地制作此代码? Spoj说我粘贴这个解决方案时超出了时间限制。

import java.math.BigInteger;
    import java.util.*;
    public class Main {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("the number of multiplications <= 1000: ");
    int n = scanner.nextInt();
    if (n <= 1000) {
    for (int i = 1; i <= n; i++) {
    System.out.print("First number to multiply");
    BigInteger l1 = new BigInteger(scanner.next());
    System.out.print("Second number to multiply");
    BigInteger l2 = new BigInteger(scanner.next());
if (l1.toString().length() == 10000 || l2.toString().length() == 10000) {
    System.err.println("numbers to multiply should be at most 10000 decimal digits each.");
    } else {
    System.out.println("Product: "+l1.multiply(l2));
    }
    }
    } else {
    System.err.println("number of multiplications should be less than or equal to 1000");
    }
    }
    }

更新:我现在使用了缓冲读卡器,但现在即使我的输出正确,我的答案也是错误的。这是我更新的代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) throws IOException{
try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("the number of multiplications <= 1000: ");
int n = Integer.parseInt(reader.readLine());
if (n <= 1000) {
for (int i = 1; i <= n; i++) {
System.out.print("First number to multiply: ");
BigInteger l1 = new BigInteger(reader.readLine());
System.out.print("Second number to multiply: ");
BigInteger l2 = new BigInteger(reader.readLine());
if (l1.toString().length() == 10000 || l2.toString().length() == 10000) {
System.err.println("numbers to multiply should be at most 10000 decimal digits each.");
} else {
System.out.println("Product: "+l1.multiply(l2));
}
}
    } else {
System.err.println("number of multiplications should be less than or equal to 1000");
}
} catch (NumberFormatException e) {
System.err.println("invalid");
}
}
}

提前致谢。

1 个答案:

答案 0 :(得分:1)

如果使用Scanner,读取java中的输入非常慢。您只能使用它输入非常小的输入问题。如果您认为输入可能更大,则应使用BufferedReaderBufferedWriter。你的算法的其余部分是正确的(虽然这个问题是为了测试自己实现的大整数而不是内置类型)。

编辑:由于你打印到system.out的所有助手输出,你得到WA。在编程比赛中,你应该只写出标准输出的答案。因此,您只需要打印乘法的结果。使用示例。您的输出应该与您的解决方案完全相同。