大数加法


public static String superAdd(String a, String b) {

if (a.length() < b.length()) {
String tmp = a;
a = b;
b = tmp;
}

int i = a.length() - 1;
int j = b.length() - 1;
int xx = 0;
int x = 0;
StringBuffer sb = new StringBuffer();

while (i >= 0 && j >= 0) {
int aa = a.charAt(i) - '0';
int bb = b.charAt(j) - '0';
int cc = aa + bb + xx;
xx = cc / 10;
x = cc % 10;
sb.append((char)(x + '0'));
i--;
j--;
}

if (i >= 0) {
for (; i >= 0; i--) {
if (xx != 0) {
sb.append((char)(((a.charAt(i) - '0') + xx)%10+'0'));
xx = ((a.charAt(i) - '0') + xx)/10;
}else{
sb.append(a.charAt(i));
}
}
}

if(xx!=0){
sb.append((char)('0'+xx));
}
sb.reverse();
return sb.toString();
}


你可能感兴趣的:(码农)