题解 | #高精度整数加法#
高精度整数加法
http://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
使用StringBuilder缓存结果 按照类似归并的思想从个位向高位慢慢进行累加,并且使用k保存进位
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str1 = sc.nextLine();
String str2 = sc.nextLine();
String str = add(str1, str2);
System.out.println(str);
}
public static String add(String str1, String str2){
StringBuilder sb = new StringBuilder();
//分别表示遍历到的str1,str2的位置,k表示进位
int i = str1.length()-1, j = str2.length()-1, k = 0;
while(i >= 0 && j >= 0){
char c1 = str1.charAt(i);
char c2 = str2.charAt(j);
int m = c1-'0'+c2-'0'+k;
sb.append(m % 10);
k = m / 10;
i--;
j--;
}
while(i >= 0){
char c1 = str1.charAt(i);
int m = c1 - '0' + k;
sb.append(m % 10);
k = m / 10;
i--;
}
while(j >= 0){
char c2 = str2.charAt(j);
int m = c2 - '0' + k;
sb.append(m % 10);
k = m / 10;
j--;
}
if(k > 0){
sb.append(k);
}
sb.reverse();
return sb.toString();
}
}