字符串转化为加法运算:
public class demo {
public static void main(String[] args) {
add("5555","5555");
}
public static void add(String a, String b){
//反转
String a1 = new StringBuffer(a).reverse().toString();
String b1 = new StringBuffer(b).reverse().toString();
int la = a1.length();
int lb = b1.length();
int maxl = la>lb? la: lb;
//结果
int[] Sum = new int[maxl+1];
Sum[0] = 0;
//进位
int t = 0;
//高位补零
if (la <lb){
for (int i = la; i< lb;i++){
a1+="0";
}
}else if (la>lb){
for (int i = lb; i < la; i++) {
b1+="0";
}
}
//相加运算
for (int i = 0; i < Sum.length-1; i++) {
int ai = Integer.parseInt(a1.charAt(i) + "");
int bi = Integer.parseInt(b1.charAt(i) + "");
int ci = Sum[i];
t = ai + bi + ci;
Sum[i]= t%10;
Sum[i+1] = t/10;
}
//输出展示
StringBuffer result = new StringBuffer();
for (int i = Sum.length-1; i >= 0; i--) {
if (i == Sum.length-1 && Sum[i] == 0) continue;
result.append(Sum[i]);
}
System.out.println(result);
}
}