方法一
这个方法就是把连个相加的数,使得他们位数相等
例如123+9787理解为0123+9787
然后用K来表示进位,这里个位数7+3==10,就需要进一位
import java.util.Scanner;
public class 加法 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.next();
String s2 = sc.next();
char[] a = s1.toCharArray();
char[] b = s2.toCharArray();
int len1 = a.length;
int len2 = b.length;
if(len1 < len2) {
char[] temp = a;
a = b;
b = temp;
}
//反正a一定是比较长的那个串
int maxlen = len1 > len2 ? len1 : len2;
int minlen = len1 > len2 ? len2 : len1;
int[] aa = new int[maxlen];
int[] bb = new int[maxlen];
int[] res = new int[maxlen];
int k = 0;//向后进位
for(int i = 0;i < maxlen;i++) {
aa[i] = a[i] - '0';
}
for(int i = 0;i < maxlen;i++) {
if(i < minlen) {
bb[i] = b[i] - '0';
}else {
bb[i] = 0;
}
}
for(int i = 0;i < maxlen / 2;i++) {
int temp = aa[i];
aa[i] = aa[maxlen - i - 1];
aa[maxlen - i - 1] = temp;
}
for(int i = 0;i < maxlen / 2;i++) {
int temp = bb[i];
bb[i] = bb[maxlen - i - 1];
bb[maxlen - i - 1] = temp;
}
for(int i = 0;i < maxlen;i++) {
int val = (aa[i] + bb[i] + k);
res[i] = val % 10;
k = val / 10;
}
String result = "";
for(int i = 0; i < maxlen;i++) {
result += res[i];
}
if(k != 0) {
result = result + "1";
}
StringBuffer sb = new StringBuffer(result);
result = sb.reverse().toString();
System.out.println(result);
}
}
方法二
char[] a 被加数,用字符数组表示,位数不限
char[] b 加数,用字符串表示,位数不限
back[] 结果,用字符数组表示
空间复杂度为O(n ^2)
import java.util.Scanner;
public class 加法 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String aa = sc.next();
String bb = sc.next();
char[] a = aa.toCharArray();
char[] b = bb.toCharArray();
char[] back = new char[100];//100位的结果
add(a, b, back);
for(int i = 0;i < back.length;i++) {
if(back[i] == '\0') break;
System.out.print(back[i]);
}
}
public static void add(char[] a,char[] b,char[] back) {
int i,j,k,up,x,y,z,l;
if(a.length > b.length) {
l = a.length + 2;
}else {
l = b.length + 2;
}
char[] c = new char[l];
i = a.length - 1;
j = b.length - 1;
k = 0;
up = 0;
while(i >= 0|| j >= 0) {
if(i < 0) {
x = '0';
}else {
x = a[i];
}
if(j < 0) {
y = '0';
}else {
y = b[j];
}
z = x - '0' + y - '0';
if(up == 1) {
z += 1;
}
if(z > 9) {
up = 1;
z %= 10;
}else {
up = 0;
}
c[k++] = (char) (z + '0');
i--;
j--;
}
if(up == 1) {
c[k++] = '1';
}
i = 0;
c[k] = '\0';
for(k-=1;k>=0;k--) {
back[i++] = c[k];
}
back[i] = '\0';
}
}
方法三
其实还可以用BigDecimal来做,这里就不给出代码了。