今天在k6k4在线编程做了一道算法题,记录一下:原文:
大整数相乘
两个大整数相乘容易溢出,现将整数用字符数组表示,模拟整数相乘的过程。如两个整数字符数组表示为: a = new char[]{‘1’, ‘9’, ‘9’}, b = new char[]{‘2’, ‘9’, ‘9’, ‘9’, ‘9’}, 结果为:c = new char[]{‘5’, ‘9’, ‘6’, ‘9’, ‘8’,’0′,’1′}。 注:大整数首位不能为0
输入、输出描述
输入:
两个大整数的字符串表示形式,排列从高位到地位,如321 的数组表示形式:new char[]{‘3’, ‘2’, ‘1’}
输出:
两个大整数相乘结果的字符数组表示形式,首位不能为0
Example
输入:
a = new char[]{‘1’, ‘9’, ‘9’}
b = new char[]{‘2’, ‘9’, ‘9’, ‘9’, ‘9’}
输出:
c = new char[]{‘5’, ‘9’, ‘6’, ‘9’, ‘8’,’0′,’1′}
解法:
import java.util.*;
public class Main {
public char[] solution(char[] a,char[] b) {
char[] c = new char[a.length + b.length];
int i, j, m, n;
int sum, carry;
m = a.length - 1;
n = b.length - 1;
for (i = m; i >= 0; i--)
a[i] -= '0';
for (i = n; i >= 0; i--)
b[i] -= '0';
carry = 0;
for (i = m + n; i >= 0; i--) {
sum = carry;
if ((j = (i - m)) < 0)
j = 0;
for (; j <= i && j <= n; j++)
sum += a[i - j] * b[j];
c[i + 1] = (char) (sum % 10 + '0');
carry = sum / 10;
}
if ((c[0] = (char) (carry + '0')) == '0') {
char[] result = new char[c.length - 1];
for (i = 1; i < c.length; i++) {
result[i - 1] = c[i];
}
return result;
} else {
return c;
}
}
}
原文:
大整数相乘