0

I am receiving inconsistent results from my function that will subtract elements in arrays of 32 digits of different lengths. Rather than starting at the end of both arrays, it is starting at the start of the second array and going to the end. I am slightly confused as to why, because my loop is starting at the end. Any help will be appreciated.

int carry = 0;
    int total = Math.max(tempArray.length, tempArrayTwo.length);
    int[] subArray = new int[total];
    for (int i = differenceArray.length - 1; i >= 0; i--) {
        int first = i < tempArray.length ? tempArray[tempArray.length - i - 1] : 0;
        int second = i >= tempArrayTwo.length ?  0 : tempTwoArray[tempTwoArray.length - i - 1];
        int difference = first - second - carry;
        carry = 0;
        if (difference < 0) {
            difference = difference + 10;
            System.out.println(difference);
            carry = 1;
        } 
        subArray[subArray.length - 1 - i] = difference;

The problem I am having is say array one has a size of 6, 46 total numbers and array two has a size of 3 (24 total numbers) is that the subtraction will start at the start of the 24th character of the first array and the first element of the second array.

(at the 24th of 46 slot of array One)

00003333 33333333 33333333 array One

10000000 00000000 00000000 arrayTwo

Instead of starting from 3 of arrayOne and 0 of arrayTwo, it will start at 0 of arrayOne and 1 of arrayTwo. Very strange, especially since it sometimes will work accordingly. The extra digits from the larger array are carried down, fyi. It's just these particular digits that get screwed up.

2
  • Were you looking for BigInteger? Commented Mar 24, 2017 at 14:08
  • Not at this time, looking for my own implementation. Commented Mar 24, 2017 at 14:39

1 Answer 1

0

Your problem is how you are indexing into your arrays

int carry = 0;
int total = Math.max(tempArray.length, tempArrayTwo.length);
int[] subArray = new int[total];
//you want subArray below, not differenceArray
for (int i = subArray.length - 1; i >= 0; i--) {
    int first = i < tempArray.length ? tempArray[tempArray.length - i - 1] : 0;
    //Line above probably should just be int first = tempArray[i];
    int second = i >= tempArrayTwo.length ?  0 : tempTwoArray[tempTwoArray.length - i - 1];
    //Line above probably should just be int second = tempTwoArray[i];
    int difference = first - second - carry;
    carry = 0;
    if (difference < 0) {
        difference = difference + 10;
        System.out.println(difference);
        carry = 1;
    } 
    subArray[subArray.length - 1 - i] = difference;
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, that was just a typo (in regards to the arrays). I am still getting the same result, however.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.