题解 | #高精度整数加法#
高精度整数加法
https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str1 = in.nextLine();
String str2 = in.nextLine();
StringBuffer sumStr = new StringBuffer();
int nextInt = 0;
int loopCount = 1;
int str2Len = str2.length();//str2的字符长度
int val1 = 0;
int val2 = 0;
//从字符串末位向前开始计算
for(int i=str1.length()-1;i>=0;i--){
val1 = Integer.parseInt(str1.charAt(i)+"");
if(str2Len >= loopCount){
val2 = Integer.parseInt(str2.charAt(str2Len-loopCount)+"");
}else{
val2 = 0;
}
//获取相加后的个位数,十位数放到下次使用
sumStr.append((val1+val2+nextInt)%10);
nextInt = (val1+val2+nextInt)/10;
loopCount++;
}
//如果str1长度小于str2
for(int i = str2Len-loopCount;i>=0;i--){
val2 = Integer.parseInt(str2.charAt(i)+"");
sumStr.append((val2+nextInt)%10);
nextInt = (val2+nextInt)/10;
}
sumStr.append(nextInt);
//将相加的字符串反转并去掉前面的0
String resultStr = sumStr.reverse().toString().replaceAll("^(0+)","");
//如果出现去除0后字符串为空,则赋值0
if("".equals(resultStr)){
resultStr = "0";
}
System.out.println(resultStr);
}
}
注意点:①要使用Integer.parseInt才能正确转化为数字,使用Integer.valueOf()会将数字变成ASCII值
②去掉字符串前面的0的正则表达式replaceAll("^(0+)","")
