简体   繁体   中英

What is the space complexity of this binary addition solution?

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(n 2 ) 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(n 2 ) because the two functions are in the same family?

After revisiting this question, I should have been more clear with my use of variables.

The time complexity of my algorithm is O(log 2 m + n 1 + n 2 ) Big O Summation where m is the decimal representation of the sum of the binary numbers. n 1 and n 2 are the number of bits, or the length of bin1 and bin2 respectively.

For Space Complexity , you have to take into account all memory allocated by your algorithm - from the stack and the heap.

When analyzing the amount of space I've used from the stack , I noticed that I've made no recursive calls that that space would be O(1) . Similarly when analyzing the amount of space I've used form the heap, it would also be O(1) because no matter the input, I always allocate the same amount of space (3 ints), using no data structures.

Therefore the space complexity of my solution is O(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM