您的位置:首页 > 编程语言 > Java开发

链家笔试题--java实现两个大整数相乘的算法

2018-03-29 16:39 351 查看
两个字符串表示两个非常大的数,请设计算法计算这两个大数的乘积,结果用字符串表示。例如S1=”7832974972840919321747983209327”,S2=”1987432091904327543957”,设计算法计算出S1*S2的结果,结果用String输出,不准用BigInter。

思路:

根据手工计算两数相乘的过程,用代码实现这个过程。注意没有考虑负数的情况。

代码如下:

import java.util.Scanner;

/**
* 两个大整数相乘求结果返回字符串。
*
*
*/
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str1 = sc.nextLine();
String str2 = sc.nextLine();
String result = getResult(str1, str2);
System.out.println(result);
}

private static String getResult(String str1, String str2) {
// 求出两个字符串的长度
int n = str1.length();
int m = str2.length();
// 定义一个数组接收结果,长度一定不会超过n+m
int num[] = new int[n + m];
// 遍历字符串的每一位,从后往前遍历,然后计算结果
for (int i = 0; i < n; i++) {
// 遍历每一位
int a = str1.charAt(n - i - 1) - '0';
// 定义一个进位
int temp = 0;
for (int j = 0; j < m; j++) {
int b = str2.charAt(m - j - 1) - '0';
// 计算 进位+num[i+j]+a*b
temp = temp + num[i + j] + a * b;
// 去余 将个位存入数组中
num[i + j] = temp % 10;
// 保存进位
temp = temp / 10;
}
// 第一轮循环结束,如果有进位,将进位放入更高的位置
num[i + m] = temp;
}
// 计算结果到底是几位数字
int i = m + n - 1;
while (i > 0 && num[i] == 0) {
i--;
}
// 定义一个字符串 将数组反过来放入字符串中
StringBuilder result = new StringBuilder();
while (i >= 0) {
result.append(num[i--]);
}
return result.toString();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  大整数相乘