使用数组添加大数
Using arrays to add large numbers
我需要使用数组将两个长度为 50 的数字相加。我相信我已经进行了正确的转换,但我不完全知道如何 return 要打印的最终总和。我的添加方法正确吗?我需要 return 类型还是可以将其用于 return 什么(void)?
import java.util.Scanner;
public class intAdding {
public static void main(String[] args) {
String x,y;
String a[] = new String[50];
String b[] = new String[50];
System.out.println("Please enter two numbers with up to 50 digits: ");
Scanner stdIn = new Scanner(System.in);
x = stdIn.next();
y = stdIn.next();
System.out.println("first number: " + x);
System.out.println("second number: " + y);
a[] = stringToIntArray(x);
a[] = stringToIntArray(y);
int[] result = new int[51];
result = null;
addnum(a, b, result);
System.out.println(result);
}
void addnum(int c[50], int d[50], int sum[51]) {
int carry=0;
int temp;
int i;
for(i=0; i<=50; i++) {
temp=c[i]+d[i]+carry;
sum[i]=temp%10;
carry=temp/10;
}
}
一个简单的方法是使用 BigInteger
。数组逻辑全部在幕后处理:
BigInteger bigX = new BigInteger(x);
BigInteger bigY = new BigInteger(y);
BigInteger sum = bigX.add(bigY);
System.out.println(sum);
由于数组是引用类型,您不必 return 显式地显示结果。 void
可以使用 addNum() 方法。您必须进行以下更改(删除带有结果的空分配)-
int[] result = new int[51];
addnum(a, b, result);
System.out.println(result);
除此之外您还需要进行以下更改 -
b[] = stringToIntArray(y); //instead of a[] = stringToIntArray(y);
但最好的方法是使用 java.math.BigInteger
。
我需要使用数组将两个长度为 50 的数字相加。我相信我已经进行了正确的转换,但我不完全知道如何 return 要打印的最终总和。我的添加方法正确吗?我需要 return 类型还是可以将其用于 return 什么(void)?
import java.util.Scanner;
public class intAdding {
public static void main(String[] args) {
String x,y;
String a[] = new String[50];
String b[] = new String[50];
System.out.println("Please enter two numbers with up to 50 digits: ");
Scanner stdIn = new Scanner(System.in);
x = stdIn.next();
y = stdIn.next();
System.out.println("first number: " + x);
System.out.println("second number: " + y);
a[] = stringToIntArray(x);
a[] = stringToIntArray(y);
int[] result = new int[51];
result = null;
addnum(a, b, result);
System.out.println(result);
}
void addnum(int c[50], int d[50], int sum[51]) {
int carry=0;
int temp;
int i;
for(i=0; i<=50; i++) {
temp=c[i]+d[i]+carry;
sum[i]=temp%10;
carry=temp/10;
}
}
一个简单的方法是使用 BigInteger
。数组逻辑全部在幕后处理:
BigInteger bigX = new BigInteger(x);
BigInteger bigY = new BigInteger(y);
BigInteger sum = bigX.add(bigY);
System.out.println(sum);
由于数组是引用类型,您不必 return 显式地显示结果。 void
可以使用 addNum() 方法。您必须进行以下更改(删除带有结果的空分配)-
int[] result = new int[51];
addnum(a, b, result);
System.out.println(result);
除此之外您还需要进行以下更改 -
b[] = stringToIntArray(y); //instead of a[] = stringToIntArray(y);
但最好的方法是使用 java.math.BigInteger
。