想要处理以下问题
String findDifference(String, String)
{
str1 - str2
}
如果
str1 = "1002456789100245678910024567891002456789100245678910024567891002456789100245678910024567891002456789100245678910024567891002456789100245678910024567891002456789";
str2 = "0022446611002244661100224466110022446611002244661100224466110022446611002244661100224466110022446611002244661100224466110022446611002244661100224466110022446611";
output = "1000010178100001017810000101781000010178100001017810000101781000010178100001017810000101781000010178100001017810000101781000010178100001017810000101781000010178"
str1 = "1002456789100245678910024567891002456789100245678910024567891002456789100245678910024567891002456789100245678910024567891002456789100245678910024567891002456789100245678910024567891002456789100245678910024567891002456789";
str2 = "0022446611000000000000224466110000000000002244661100000000000022446611000000000000224466110000000000002244661100000000000022446611000000000000224466110000000000002244661100000000000022446611000000000000224466110000000000";
output = "1000010178100245678910000101781002456789100001017810024567891000010178100245678910000101781002456789100001017810024567891000010178100245678910000101781002456789100001017810024567891000010178100245678910000101781002456789"
是否有比Traversing Str1 ctr(0,n-1)更好/优化的方式Integer.parseInt(str1 [ctr]) - Integer.parseInt(str2 [ctr])并将答案附加到输出[ctr]?
BigInteger会处理这么大的数字吗?
答案 0 :(得分:3)
你交出了非常大的数字 - 大于int
的数字。如果你想处理任意大数字(内存允许),你需要使用BigInteger:
public static String findDifference(String str1, String str2) {
return new BigInteger(str1).subtract(new BigInteger(str2)).toString();
}
请注意,您的示例有误 - 输出不是str1 - str2
的正确结果。
如果我使用这个小驱动程序:
public static void main(String[] args) {
System.out.println(findDifference("10024567891002456789", "00224466110000000000"));
System.out.println(findDifference("1002456789", "0022446611"));
System.out.println(findDifference("1234567", "0111100"));
}
我收到此输出,并使用计算器验证显示这是正确的:
9800101781002456789
980010178
1123467