private static int[] sub(int[] sub1, int[] sub2) { if (sub2.length == 1 && sub2[0] == 0) return sub1; int[] result = new int[sub2.length]; for (int i = 0; i < sub2.length; i++){ if (sub2[i] == 1) result[i] = 0; else result[i] = 1; } int[] one = {1}; result = add(result, one); result = add(sub1, result); if (result[result.length - 1] == 1) result[result.length - 1] = 0; return trimZeroes(result); } private static int[] trimZeroes(int[] toTrim){ if (toTrim[toTrim.length - 1] == 0) { int firstOne = 0; boolean firstOneReached = false; for (int i = toTrim.length - 1; !firstOneReached && i >= 0; i--){ if (toTrim[i] == 1){ firstOne = i; firstOneReached = true; } } int[] result = new int[firstOne + 1]; for (int i = 0; i < result.length; i++){ result[i] = toTrim[i]; } return result; } else return toTrim; } private static int[] add(int[] addend1, int[] addend2) { int[] result = new int[Math.max(addend1.length, addend2.length) + 1]; for (int i = 0; i < Math.min(addend1.length, addend2.length); i++){ result[i] = addend1[i] + addend2[i]; } if (addend1.length == addend2.length) { return carryCorrect(result); } else if (addend1.length > addend2.length) { result[addend1.length - 1] = addend1[addend1.length - 1]; return carryCorrect(result); } else { result[addend2.length - 1] = addend1[addend2.length - 1]; return carryCorrect(result); } } private static int[] carryCorrect(int[] toCorrect) { // we're starting at 1 because the first digit will never need correction for (int i = 0; i < toCorrect.length; i++){ // affecting i+1 is normally dangerous as it can lead to an index out of bounds exception // except here we know that most significant digit won't ever trigger these if-statements if (toCorrect[i] > 1) { // if the entry is an even number, we know that this should be a binary 0 if (toCorrect[i]%2 == 0) { toCorrect[i+1] += toCorrect[i]/2; // carry the total complete bits to the next column toCorrect[i] = 0; // otherwise the entry is an odd number, so } else { toCorrect[i+1] += (toCorrect[i] - 1)/2; // carry the total complete bits to the next column toCorrect[i] = 1; } } } return trimZeroes(toCorrect); }