Facebook

  www.facebook.com
Work in HR? Unlock Free Profile

Facebook Software Engineer Intern Interview Question

I interviewed in Menlo Park, CA and was asked:
"Given two strings representing integer numbers ("123" , "30") return a string representing the sum of the two numbers ("153")"
Add Tags [?]
Answer

Part of a Software Engineer Intern Interview Review - one of 1,076 Facebook Interview Reviews

Answers & Comments

0
of 7
votes

I don't understand...it's a very stupid question!

return Integer.toString(Integer.parseInt("123") + Integer.parseInt("30));

- Matteo Gobbi on Oct 5, 2013
0
of 0
votes

It's not stupid a stupid question. What if the strings have 10000 characters?

- Anonymous on Oct 6, 2013
0
of 0
votes

It's not stupid question, but it's not hard either.

I believe the way to do it is to implement the manual addition process by looping through the digits starting from the right to left and adding them one by one. This is an O(N) operation. I'm not sure if there is a better way to do it.

- Anonymous on Oct 7, 2013
0
of 1
vote

lol it is a stupid question i agree.
All you have to do is parse the strings add em parse em again and return em

- Anonymous on Oct 29, 2013
0
of 0
votes

It is basic but yet not stupid.
I assume that the interviewer asked to implement atoi and itoa (in case the interview was in C/C++).

- Anonymous on Oct 30, 2013
3
of 3
votes

The interviewer wanted a loop through the digits starting form right to left, adding them one by one, and keeping track of the carriage.

- Anonymous on Oct 30, 2013
2
of 2
votes

public static String sumStrings(String a, String b){
        char[] num1 = a.toCharArray();
        char[] num2 = b.toCharArray();

        int i = num1.length - 1;
        int j = num2.length - 1;

        StringBuilder sumString = new StringBuilder();
        int carry = 0;

        while(i >= 0 || j >= 0){
            int d1 = 0;
            int d2 = 0;

            if (i >= 0) d1 = num1[i--] - '0';
            if (j >= 0) d2 = num2[j--] - '0';

            int sum = d1 + d2 + carry;
            if (sum >= 10){
                carry = sum / 10;
                sum = sum % 10;
            }else carry = 0;

            sumString.insert(0, sum);
        }

        return sumString.toString();
    }

- Luca Lupo on Mar 1, 2014

To comment on this question, Sign In with Facebook or Sign Up

Tags are like keywords that help categorize interview questions that have something in common.