I am working on an interview problem from Facebook Software Engineer
The Problem: Write a function which given two binary numbers as strings returns the sum of them in binary
Here is my solution in Java(Tested it, It works!!!)
private static String sum(String bin1, String bin2)
{
int dec1 = binToDec(bin1);
int dec2 = binToDec(bin2);
int sumTo = dec1 + dec2;
StringBuilder bin = new StringBuilder();
do {
bin.append(sumTo%2);
sumTo = sumTo/2;
}while(sumTo > 0);
return bin.reverse().toString();
}
private static int binToDec(String bin)
{
int result = 0;
int len = bin.length();
for(int rep = len-1; rep >= 0; rep--) {
int multiplyBy = bin.charAt(rep) == '1' ? 1 : 0;
result += multiplyBy * Math.pow(2, len-1-rep);
}
return result;
}
I am trying to analyze the time and space complexity of the sum. I know that the time complexity of my algorithm would just be O(logn) because of the binary conversion.
Like usual, I am having a hard time with space complexity. I know that the space complexity would just depend on the memory I allocated from the heap, in this case the string to represent the binary sum result
I know that String concatenation is an expensive operation because it requires copying 1 chars, then 2 chars, then finally logn chars. I know that traditional String concatenation runs in O(n2) space. Would it be the same here?
I tried doing the calculations myself
1 + 2 + 3 +.... logn-1 + logn <BR>
logn + logn-1 + ....1<BR>
logn(logn + 1)/2
and got the final result of logn(logn + 1)⁄2 which would be O((logn)2). Is that the right space complexity for this algorithm? Or is it just O(n2) because the two functions are in the same family?