Hello, :?:
I need help with adding int arrays
i got the everything working except for when i need to carry more than once and if the carry isn't in the ones digit
honestly i can't think of anything :$
any ideas, suggestion, code would be welcomed
public class BCD {
private int[] digits;
BCD(int num){
int DIGIT=num%10;
num=num/10;
digits=new int[1];
digits[0]=DIGIT;
while(num>0){
DIGIT=num%10;
addADigit(DIGIT);
num=num/10;
}
public void addADigit(int newdigit){
int[] Digi= new int[digits.length+1];
Digi[digits.length]=newdigit;
for(int i=0; i<digits.length; i++){
Digi[i]=digits[i];
}
digits = Digi;
}
public BCD addBCDs(BCD other){
int[] dig={};
BCD addedBCD=new BCD(dig);
//int[] carry={};
int carry=0;
int digit1=0;
int length1=other.numberOfDigits();
int length2=digits.length;
int longerLength;
if (length1==length2){
longerLength=length1;
for(int d = 0; d <longerLength ;d++){
digit1=other.nthDigit(d)+digits[d];
addedBCD.addADigit(digit1);
}
}else if(length1>length2){
longerLength=length1;
int mlength=length1-length2;
System.out.println(mlength);
for(int c = mlength-1; c <= longerLength ;c--){
digits[c]=0;
// System.out.println("digits: "+digits);
}
for(int d = 0; d <longerLength ;d++){
digit1=other.nthDigit(d)+digits[d];
addedBCD.addADigit(digit1);
// System.out.println("final[] "+addedBCD);
}
}else if(length1<length2){
longerLength=length2;
for(int c =length2-length1; c <= longerLength ;c++){
other.addADigit(0);
}
for(int d = 0; d <longerLength ;d++){
digit1=other.nthDigit(d)+digits[d];
addedBCD.addADigit(digit1);
}
}
return addedBCD;
}
public static void main(String[] args) {
int[] case1={36};
int[] case2={21};
int[] case3={123};
int[] case4={1234};
int[] case5={123450};
int[] case6={1234567};
BCD test1=new BCD(case1);
BCD test2=new BCD(case2);
BCD test3=new BCD(case3);
BCD test4=new BCD(case4);
BCD test5=new BCD(case5);
BCD test6=new BCD(case6);
BCD addA=new BCD(0);
BCD addB=new BCD(367);
BCD addC=new BCD(355);
System.out.println(addA.addBCDs(addA)); // THIS WORKS
System.out.println(test1.addBCDs(addA)); // THIS WORKS
System.out.println(addA.addBCDs(test2)); // THIS WORKS
System.out.println(test1.addBCDs(test3)); // THIS WORKS
System.out.println(test6.addBCDs(test5)); // THIS WORKS
System.out.println(test5.addBCDs(test6)); // THIS WORKS
System.out.println(addB.addBCDs(addC)); // Doesn't work
}
}
This is the output that i get:
0
36
21
159
1358017
1358017
61112 <-- This is the only test case that doesn't work
I think that it is printing the digits it is supposed to carry the answer should be 722
6+1, 1+1, 2
it carries when there is only 1 carry
:confused:
Thanks in advance for any help!