兩個陣列相加存入第三個陣列(面試題)
阿新 • • 發佈:2019-01-01
public class CopyArray {
public int[] add(int[] a, int[] b) {
if (a.length == b.length) {
for(int i=0;i<a.length-1;i++){
a[i]=a[i]+b[i];
if(a[i]>9){
a[i]=a[i]%10;
a[i+1]=a[i+1]+1;
}
}
a[a.length-1]=a[a.length-1]+b[b.length-1];
if(a[a.length-1]>9){
a[a.length-1]=a[a.length-1]%10;
int[] c=new int[a.length+1];
for(int i=0;i<a.length;i++){
c[i]=a[i];
}
c[c.length-1]=1;
return c;
}else{
return a;
}
} else {
int[] bigger = a.length > b.length ? a : b;
int[] smaller = a.length < b.length ? a : b;
int temp = bigger.length - smaller.length;
for(int i=0;i<=smaller.length-1;i++){
bigger[i] = smaller[i] + bigger[i];
if (bigger[i] > 9) {
bigger[i] = bigger[i] % 10;
bigger[i + 1] = bigger[i + 1] + 1;
}
}
for (int i = smaller.length; i < bigger.length-1; i++) {
if (bigger[i] > 9) {
bigger[i] = bigger[i] % 10;
bigger[i - 1] = bigger[i - 1] + 1;
}
}
if (bigger[bigger.length-1] > 9) {
bigger[bigger.length-1] = bigger[bigger.length-1] % 10;
int[] c = new int[bigger.length + 1];
for (int i = 0; i < bigger.length; i++) {
c[i + 1] = bigger[i];
}
c[bigger.length-1] = 1;
return c;
} else {
return bigger;
}
}
}
public static void main(String[] args){
int[] a={1,3,6,8,4,5,7};
int[] b={2,4,6,7,8};
CopyArray copy=new CopyArray();
int[] c=copy.add(a,b);
for(int i=0;i<c.length;i++){
System.out.println(c[i]);
}
}
}
public int[] add(int[] a, int[] b) {
if (a.length == b.length) {
for(int i=0;i<a.length-1;i++){
a[i]=a[i]+b[i];
if(a[i]>9){
a[i]=a[i]%10;
a[i+1]=a[i+1]+1;
}
}
a[a.length-1]=a[a.length-1]+b[b.length-1];
if(a[a.length-1]>9){
a[a.length-1]=a[a.length-1]%10;
int[] c=new int[a.length+1];
for(int i=0;i<a.length;i++){
c[i]=a[i];
}
c[c.length-1]=1;
return c;
}else{
return a;
}
} else {
int[] bigger = a.length > b.length ? a : b;
int[] smaller = a.length < b.length ? a : b;
int temp = bigger.length - smaller.length;
for(int i=0;i<=smaller.length-1;i++){
bigger[i] = smaller[i] + bigger[i];
if (bigger[i] > 9) {
bigger[i] = bigger[i] % 10;
bigger[i + 1] = bigger[i + 1] + 1;
}
}
for (int i = smaller.length; i < bigger.length-1; i++) {
if (bigger[i] > 9) {
bigger[i] = bigger[i] % 10;
bigger[i - 1] = bigger[i - 1] + 1;
}
}
if (bigger[bigger.length-1] > 9) {
bigger[bigger.length-1] = bigger[bigger.length-1] % 10;
int[] c = new int[bigger.length + 1];
for (int i = 0; i < bigger.length; i++) {
c[i + 1] = bigger[i];
}
c[bigger.length-1] = 1;
return c;
} else {
return bigger;
}
}
}
public static void main(String[] args){
int[] a={1,3,6,8,4,5,7};
int[] b={2,4,6,7,8};
CopyArray copy=new CopyArray();
int[] c=copy.add(a,b);
for(int i=0;i<c.length;i++){
System.out.println(c[i]);
}
}
}