题目描述:
给定两个大于1000位长的字符串,计算他们作为数字进行相加(超过long的范围)
思路分析:
很常见的题目。
思路1:使用java很容易,直接使用BigInteger进行相加
思路2:借助于数组
- String转int数组
- 两个int数组末尾相加
- 存在超过10的数,进行进位
代码
package xyz.gsdn.qianFeng;
import xyz.gsdn.utils.CollectionUtils;
import java.math.BigInteger;
/**
* @author shen_i
* @Date: 2020/8/30 0030
* @Time: 21:07
* @Description:
* 大数相加
*/
public class BigNumberAdd {
//方法1:java的api
String bigInteger(String num1 , String num2){
BigInteger bigInteger1 = new BigInteger(num1);
BigInteger bigInteger2 = new BigInteger(num2);
BigInteger result = bigInteger1.add(bigInteger2);
return result.toString();
}
//方法2:
String arrayAdd(String num1 , String num2){
// String数组转为int数组
int[] num1_int = null;
int[] num2_int = null;
if (num1.length() >= num2.length()) {
num1_int = new int[num1.length()];//长
num2_int = new int[num2.length()];//短
}
else {
num1_int = new int[num2.length()];
num2_int = new int[num1.length()];
}
//转int
for (int i = 0; i < num1.length(); i++) {
num1_int[i] = (int) (num1.charAt(i) - '0');
}
for (int i = 0; i < num2.length(); i++) {
num2_int[i] = (int) (num2.charAt(i) - '0');
}
//结果集:长度为两个String中最长的长度再加一
int[] result = new int[num1_int.length+1];
for (int i = 0; i < num1_int.length; i++) {
result[i] = num1_int[num1_int.length-i-1];
}
for (int i = 0; i < num2_int.length;i++) {
//result中可能存在大于10的数
result[i] += num2_int[num2_int.length-i-1];
}
//处理大于10
for (int i = 0; i < num1_int.length+1; i++) {
if (result[i] > 9)
{
result[i] %= 10;
result[i+1] += 1;
}
}
//处理result是倒转的,应从后往前读
StringBuffer stringBuffer = new StringBuffer();
for (int i = result.length-1; i >= 0; i--) {
//可能为0
if (i == result.length-1 && result[result.length-1] == 0)
{
continue;
}
stringBuffer.append(result[i]);
}
return stringBuffer.toString();
}
public static void main(String[] args) {
String num1 ="9999999";
String num2 = "4234234";
System.out.println("预期结果:"+(9999999+4234234));
// String s = new BigNumberAdd().bigInteger(num1, num2);
String s = new BigNumberAdd().arrayAdd(num1, num2);
System.out.println(s);
}
}