多位十进制数相加问题

今天看到一道题目,关于两个n位十进制数的加法问题,不禁想起了n久前在一次华为的面试中被问起两个50位的整数相乘的问题。唉,一个小小的问题,说起来虽然简单,实际做的时候却有很多细节要注意,我平时还是空想大于实干了。

不曾想到,这段代码,来来回回居然花了几个小时的时间。

//(#)NBitDecimalIntegerAlgorithm.java

public class NBitDecimalIntegerAlgorithm {

/**
* addition
*
* @param a the first addend
* @param b the second addend
*
* @return the sum
*/

public static int[] addAB(int[] a, int[] b) {
int maxLength = a.length;
if (a.length < b.length) {
maxLength = b.length;
}

int[] integerA = new int[maxLength];
int[] integerB = new int[maxLength];

for (int i = 0; i < a.length; i++) {
integerA[i] = a[i];
}

for (int i = 0; i < b.length; i++) {
integerB[i] = b[i];
}

int[] sum = new int[maxLength + 1];

int carry = 0;
for (int i = 0; i < maxLength; i++) {
int tempSum = integerA[i] + integerB[i] + carry;
int remainder = tempSum % 10;
carry = tempSum / 10;

sum[i] = remainder;
}

sum[sum.length - 1] = carry;
return sum;

}

/**
* multiplication
*
* @param a the first factor
* @param b the second factor
*
* @return the product
*/

public static int[] multiplyAB(int[] a, int[] b) {
int[] sumProduct = new int[a.length + 1];

for (int i = 0; i < b.length; i++) {
int[] product = multiplyAB(a, b[i], i);
sumProduct = addAB(sumProduct, product);
}

return sumProduct;
}


public static String parseStr(int[] v) {
String str = "";
for (int i = v.length; i > 0; i--) {
if (v[i - 1] != 0 || !str.equals("")) {
str += v[i - 1];
}
}
return str;
}

private static int[] multiplyAB(int[] a, int b, int bIndex) {
int[] product = new int[a.length + 1 + bIndex];
int carry = 0;
for (int i = 0; i < a.length; i++) {
int tempProduct = a[i] * b + carry;
int remainder = tempProduct % 10;
carry = tempProduct / 10;

product[bIndex + i] = remainder;
}
product[bIndex + a.length] = carry;
return product;
}

public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 3, 5}; //3501987654321
int[] b = {1, 2, 3, 4, 5, 6, 7, 8, 9}; //987654321


int[] s = addAB(a, b);
int[] p = multiplyAB(a, b);

System.out.println(parseStr(a));
System.out.println(parseStr(b));
System.out.println(parseStr(s));
System.out.println(parseStr(p));
}

}

标签: | edit post
0 Responses