2016-11-27 47 views
1

我正在尝试编写一个涉及函数的代码,该函数以字符串形式输入数字,并将该输入的其余部分以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")); 
    } 
} 
+0

很适合您编辑和指定错误。我只瞥了一眼,发现在整个BigInteger强制下来之后你使用了模数。我现在已经发现了一部分问题。 – Makoto

+0

(我自己在运行后实际添加了特定的错误) – qxz

+0

@qxz:好的,谢谢你。 – Makoto

回答

2

你怎么粘贴这个字符串?它看起来像包含很多zero-width spaceszero-width non-joiners

我说“貌似”;实际上,如果您打印出字符串数组的内容,您将只能看到这些字符串的内容,或者使用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当你想要做一个模(因为相信我,使用%是不会给你正确的答案与一个大的整数)。