Here's some other points to consider.
Checking for empty string and null seems to be redundant. The compiler treats them the same.
Your check for null, only checks if both are null. For completion it would be better to also check if either is null.
I think it would be more performant to use a char array set to the longest length possible(length of longest string plus 1) and change the value at each index, rather than constantly appending to the StringBuilder.
You aren't checking for malformed strings.
You aren't handling strings of different lengths.
With all these taken into consideration your code could look something like this:
final static char ZERO_CHAR_VALUE = '0';
final static char ONE_CHAR_VALUE = '1';
final static char DEFAULT_CHAR_VALUE = '\0';
public static String AddBinary(String inValA, String inValB) {
if (inValA == null) {
if (inValB == null) {
return null;
}
return inValB;
}
if (inValB == null) {
return inValA;
}
int aIndex = inValA.length() - 1;
int bIndex = inValB.length() - 1;
int longestLength = Math.max(aIndex, bIndex) + 2;
char[] tempOutVal = new char[longestLength];
int tempOutIndex = tempOutVal.length - 1;
char aTemp;
char bTemp;
for (; aIndex >= 0 && bIndex >= 0; aIndex--, bIndex--, tempOutIndex--) {
aTemp = inValA.charAt(aIndex);
BinaryCharValidator(aTemp, inValA);
bTemp = inValB.charAt(bIndex);
BinaryCharValidator(bTemp, inValB);
SetValue(aTemp, bTemp, tempOutVal, tempOutIndex);
}
if (aIndex >= 0) {
for (; aIndex >= 0; aIndex--, tempOutIndex--) {
aTemp = inValA.charAt(aIndex);
BinaryCharValidator(aTemp, inValA);
bTemp = ZERO_CHAR_VALUE;
SetValue(aTemp, bTemp, tempOutVal, tempOutIndex);
}
}
if (bIndex >= 0) {
for (; bIndex >= 0; bIndex--, tempOutIndex--) {
aTemp = ZERO_CHAR_VALUE;
bTemp = inValB.charAt(bIndex);
BinaryCharValidator(bTemp, inValB);
SetValue(aTemp, bTemp, tempOutVal, tempOutIndex);
}
}
return new String(tempOutVal);
}
public static void SetValue(char aVal, char bVal, char[] outVal, int outIndex) {
if (outVal[outIndex] == DEFAULT_CHAR_VALUE) {
outVal[outIndex] = ZERO_CHAR_VALUE;
}
int aTemp = aVal - ZERO_CHAR_VALUE;
int bTemp = bVal - ZERO_CHAR_VALUE;
int outTemp = outVal[outIndex] - ZERO_CHAR_VALUE;
int sum = aTemp + bTemp + outTemp;
outVal[outIndex] = (char) ((sum % 2) + ZERO_CHAR_VALUE);
if (sum > 1) {
outVal[outIndex - 1] = ONE_CHAR_VALUE;
} else {
outVal[outIndex -1] = ZERO_CHAR_VALUE;
}
}
public static void BinaryCharValidator(char toCheck, String input) {
if (!(toCheck == ZERO_CHAR_VALUE || toCheck == ONE_CHAR_VALUE)) {
throw new IllegalArgumentException(String.format("Malformed string(only 1's and 0's allowed). The string is \"%s0\"", input));
}
}
null
first) otherwise you will get NPE on checkinglength
\$\endgroup\$