Facebook Interview Question: Write a function that takes i... | Glassdoor

Interview Question

Software Engineer Intern Interview(Student Candidate) Palo Alto, CA

Write a function that takes in two binary strings and

  returns their sum (also a binary string).
Answer

Interview Answer

2 Answers

This post has been removed.
Please see our Community Guidelines or Terms of Service for more information.

0

#include
#include

using namespace std;

string findBinSum(string a, string b) {
/*
    Iterate through strings and find integer values.
    Find sum. Convert sum back to binary string.
*/
    int sizeA = a.size();
    int sizeB = b.size();
    int valA =0;
    int valB =0;
    for (int i=sizeA-1; i >= 0;i--)
    {
        if (a[i] == '1') {
            valA += (int)pow((double)2,(double)(sizeA-1-i));
        }
    }
    for (int k=sizeB-1; k >= 0;k--)
    {
        if (b[k] == '1') {
            valB += (int)pow((double)2,(double)(sizeB-1-k));
        }
    }
    cout =0; j--) {
        numUsed = (int)pow((double)2,(double)j);
        if ( sum-numUsed >= 0) {
            sum -= numUsed;
            answer += "1";
        }
        else {
            answer += "0";
        }
    }
    return answer;
}

int main(){
    string binary1 = "1011";
    string binary2 = "1011";

    string answer = findBinSum(binary1,binary2);
    cout << "sum: " << answer << endl;
}

Tim on Dec 21, 2011

Add Answers or Comments

To comment on this, Sign In or Sign Up.