处理大数字时出现运行时错误

时间:2016-11-27 02:58:21

标签: java

我正在尝试为涉及函数的问题编写代码,该函数将输入数字作为字符串,并在将7除以int时返回该输入的其余部分。

虽然代码适用于较小的数字,但在处理大数字作为输入时会引发运行时错误,如下所示。

Runtime error   time: 0.04 memory: 711168 signal:-1

Exception in thread "main" java.lang.NumberFormatException: For input string: "5‌​449495"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.math.BigInteger.<init>(BigInteger.java:470)
    at java.math.BigInteger.<init>(BigInteger.java:597)
    at Ideone.remainderWith7(Main.java:13)
    at Ideone.main(Main.java:22)

我的代码如下..

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone {
    int remainderWith7(String num) {
        // Your code here
        java.math.BigInteger bg = new java.math.BigInteger(num);
        //System.out.println(num);
        Integer n = bg.intValue();
        return (int) n % 7;
    }

    public static void main(String[] args) throws java.lang.Exception {
        // your code goes here
        Ideone id = new Ideone();
        System.out.println(id.remainderWith7("56495654565052555054535456545355495650575755555757575350505‌​44949525452505653565‌​54949515453545151525‌​15050575749545453535‌​54954555157565253514‌​94949495155515455545‌​65555575452555157505‌​55557495050564952514‌​95051505752545155495‌​65156515750555450545‌​35549535551525149535‌​25654525554535154515‌​05251575251494956515‌​35255515450515553515‌​15657545054505357535‌​55654575549575349565‌​351575054"));
    }
}

1 个答案:

答案 0 :(得分:2)

如何粘贴该字符串?它看起来像包含很多zero-width spaceszero-width non-joiners

我说&#34;看起来像#34 ;;实际上,如果你用Arrays.toString打印出字符串数组的内容并将该长字符串封装在一个变量中,或者如果你进行了检查,那么你只能看到那些内容。它带有调试器。

归根结底,那是什么导致你误入歧途; Java正在尝试将这些Unicode字符转换为数字,并且由于它们不是数字,因此它们会转换为-1。这就是你的代码破解的原因,这也是为什么它没有立即显示为什么它破坏了。该字符串中的字符数量超过了您立即相信的字符数。

修复方法是从字符串中删除这些字符。

String num = ""; // enter your long number here; not repeating it for brevity's sake
num = num.replace("\u200C", "").replace("\u200B", "");

现在您可以回到代码中的其他问题,例如当您想要进行模数时​​不使用BigInteger.mod(因为信任我,使用% ain& #39; t会给你一个正确答案的正确答案。