大数相加
比如远超long的数字相加,求其结果,需要用到数组,通过进位去实现
package algorithm.bignumbersum;
public class BigNumberSum {
/**
* 字符数组翻转
* 12345 3 04 13 22
* 1234 2 03 12
*
* 同时进行末尾补零,方便下面的运算
*/
public static int[] reverse(String str, int maxLen){
char[] chars = str.toCharArray();
int[] array = new int[maxLen];
for (int i = chars.length-1 ; i >=0; i--) {
array[chars.length-i-1] = chars[i]-'0';
}
return array;
}
//去掉翻转后高位的零
public static String reverse(int[] ints){
StringBuffer sb = new StringBuffer();
for (int i = ints.length-1; i >=0; i--) {
if(ints[i]!=0){
sb.append(ints[i]);
}else{
continue;
}
}
return sb.toString();
}
/**
* 大整数相加
* 思路拆分成数组 然后进位
*/
public static String bigNumberSum(String num1,String num2){
/**
* 先把数组翻转
* 12345+123 可以转换成 54321+321 从左向右做加法
*
*/
int maxLen = num1.length()>num2.length()?num1.length():num2.length();
int[] n1 = reverse(num1,maxLen);
int[] n2 = reverse(num2,maxLen);
int[] res = new int[maxLen+1];
for (int i = 0; i < maxLen; i++) {
int temp = n1[i] + n2[i];
//考虑 十进制 进位问题
if(temp>=10) {
res[i + 1] = 1;
temp -=10;
}
res[i]=temp;
}
return reverse(res);
}
public static void main(String[] args) {
//12345+123 = 12468
System.out.println(bigNumberSum("12345","123"));
}
}
不会,我可以学;落后,我可以追赶;跌倒,我可以站起来!