java算法题,有会算的帮小弟解决下
发布网友
发布时间:2022-05-16 01:49
我来回答
共4个回答
热心网友
时间:2023-10-08 21:17
-法很容易,直接作为字符串就好了
下面是假定number1比较大,不确定的话前面加个判断就好了
没有上机验证过,大体不会有错
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
StringBuffer sb = new StringBuffer();
sb.append("1");
for (int i=0;i<100;i++){
sb.append("0000000000");
}
String bigNum = sb.toString();
String num1 = scanner.next(Pattern.compile("\\d+"));
String num2 = scanner.next(Pattern.compile("\\d+"));
num1 = num1.replaceFirst("^0*", "");
num2 = num2.replaceFirst("^0*", "");
if (compare(num1, num2)<0){
System.out.println("num1<num2");
String tmp = num1;
num1 = num2;
num2 = tmp;
}
switch (compare(num1, bigNum)){
case 1:
System.out.println("num1>1.0E1000");
break;
case -1:
System.out.println("num1<1.0E1000");
break;
default:
System.out.println("num1=1.0E1000");
}
switch (compare(num2, bigNum)){
case 1:
System.out.println("num2>1.0E1000");
break;
case -1:
System.out.println("num2<1.0E1000");
break;
default:
System.out.println("num2=1.0E1000");
}
char[] c1 = num1.toCharArray();
char[] c2 = num2.toCharArray();
int len1 = c1.length;
int len2 = c2.length;
for (int i=len1-1, j=len2-1;i>=0 && j>=0;i--,j--){
if (c1[i] >= c2[j])
c1[i] = (char)(c1[i] - c2[j] + '0');
else{
c1[i] = (char)(c1[i] + 10 - c2[j] + '0');
for (int k=i-1;k>=0;k++){
if (c1[k]>'0') {
c1[k] = (char)(c1[k] - 1);
break;
}
}
}
}
System.out.println(num1 + "-" + num2 + "=" + new String(c1));
}
public static int compare(String num1, String num2){
System.out.println(num1.length() + "," + num2.length());
if (num1.length()<num2.length()){
return -1;
}else if (num1.length()==num2.length()){
return num1.compareTo(num2);
}else{
return 1;
}
}
热心网友
时间:2023-10-08 21:17
10的1000次方?你知道这个数有多大吗?10的8次方已经1亿了,10的1000次方就是1亿的125次方,你认为你的CPU能处理这种比天文数字还天文数字的数据吗?
热心网友
时间:2023-10-08 21:17
java里有大数计算的包
热心网友
时间:2023-10-08 21:18
BigInteger