例题:
输入:“123”,“234”
输出:“357”
[4,3,3,2,0,0,0]
,我们需要考虑如何屏蔽掉这些‘0’,不让它出现在最终结果。下面的代码使用了一个布尔型变量来完成“屏蔽”工作。 public static void main(String[] args) {
String bigA="1230000000";
String bigB="9780000000";
System.out.println(bigNumberSum2(bigA,bigB));
}
public static String bigNumberSum2(String s1,String s2){
int maxLen=s1.length()>s2.length()?s1.length():s2.length();
int[] res=new int[maxLen+1];
int[] arr1=new int[maxLen];
for (int i = s1.length()-1; i >=0 ; i--) {
arr1[s1.length()-1-i]=s1.charAt(i)-'0';
}
int[] arr2=new int[maxLen];
for (int i = s2.length()-1; i >=0 ; i--) {
arr2[s2.length()-1-i]=s2.charAt(i)-'0';
}
int plus=0;
int temp=0;
for (int i = 0; i < maxLen; i++) {
temp=arr1[i]+arr2[i]+plus;
res[i]=temp%10;
plus=temp/10;
}
res[maxLen]=plus;
StringBuilder builder=new StringBuilder();
boolean firstNonzero=false;// !!是否遇到第一个非零位,初始化为“还未遇到”
for (int i = res.length-1; i >=0 ; i--) {
if(!firstNonzero){
if(res[i]==0){
continue;
}
firstNonzero=true; // 遇到了第一个非零位!!
}
builder.append(res[i]);
}
return builder.toString();
}