I'm looking for code-review, optimizations and best practices. This code is a Java adaptation of code on geeksforgeeks.org. Please verify if space complexity is \$O(n)\$ where n is number of bits, and aux complexity is \$O(1)\$, since no temporary space was needed. Whatever space was needed was used for return value not for temporary purpose. Rectify my understanding of space and aux complexity if wrong.
public class AddBinaryStrings {
public static String addBinaryStrings(String num1, String num2) {
final StringBuilder sum = new StringBuilder(Math.max(num1.length(), num2.length()) + 1);
String shortNum;
String longNum;
if (num1.length() < num2.length()) {
shortNum = num1;
longNum = num2;
} else {
shortNum = num2;
longNum = num1;
}
int carry = 0;
int i = longNum.length() - 1;
int j = shortNum.length() - 1;
for (; j >= 0; j--, i--) {
int num1Digit = longNum.charAt(i) - '0';
int num2Digit = shortNum.charAt(j) - '0';
sum.append(num1Digit ^ num2Digit ^ carry);
carry = (num1Digit & num2Digit) | (num1Digit & carry) | (num2Digit & carry);
}
for (; i >= 0; i--) {
int num1Digit = longNum.charAt(i) - '0';
sum.append(num1Digit ^ carry);
carry = num1Digit & carry;
}
if (carry == 1) {
sum.append(1);
}
return sum.reverse().toString();
}
}
public class AddBinaryStringTest {
@Test
public void testCarry() {
assertEquals("1000" , AddBinaryStrings.addBinaryStrings("101","11"));
}
@Test
public void testNoCarry() {
assertEquals("1101", AddBinaryStrings.addBinaryStrings("1000", "101"));
}
}
new BigInteger(num1, 2).add(new BigInteger(num2, 2)).toString(2)
? – 200_success♦ Apr 6 at 2:28BigInteger
needs some space? However, theStringBuilder
needs some additional memory, too, and it needs surely more than theBigInteger
s. The OP's claim "Whatever space was needed was used for return value not for temporary purpose" is wrong, the return value is theString
. – maaartinus Apr 6 at 4:54