利用上篇写的StringOrder,再写一个"无聊的“面试老喜欢出的超多位数的String相加,代码如下:
public class StringAdd {
public static void main(String[] args){
String a1 = "112323441";
String a2 = "2000";
System.out.print(new StringAdd().realAdd(a1, a2));
}
public String realAdd(String a1, String a2){
String[] adds = new String[]{a1,a2};
if(adds[0].length() > adds[1].length()){
changeNumber(adds);
}
StringOrder s1Order = new StringOrder(adds[0],false);
StringOrder s2Order = new StringOrder(adds[1],false);
String[] cacheResult = new String[adds[1].length()+1];
int cache = 0;
for(int i=0;i<adds[1].length();i++){
String cachea1 = s1Order.stringNext();
int _cachea1 = cachea1 == null?0:Integer.parseInt(cachea1);
int _cachea2 = Integer.parseInt(s2Order.stringNext());
cache = _cachea1 + _cachea2;
if("1".equals(cacheResult[adds[1].length()-i])){
cache++;
}
if(cache < 10){
cacheResult[adds[1].length()-i]= cache + "";
}else{
cacheResult[adds[1].length()-i]= cache % 10 + "";
cacheResult[adds[1].length()-i-1]= cache / 10 + "";
}
}
StringBuffer result = new StringBuffer();
for(int i=0;i<cacheResult.length;i++){
if(cacheResult[i]!=null){
result.append(cacheResult[i]);
}
}
return result.toString();
}
private void changeNumber(String[] adds){
String s3 = adds[0];
adds[0] = adds[1];
adds[1] = s3;
}
}