Facebook

www.facebook.com

Interview Question

Software Engineer Intern Interview Menlo Park, CA

Given two strings representing integer numbers

  ("123" , "30") return a string representing the sum of the two numbers ("153")
Answer

Interview Answer

9 Answers

0

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
1

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

Anonymous on Oct 6, 2013
0

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

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

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

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
3

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
0

public class StringToInt {
    public int stringToInt(String str) {
        int tens = 1;
        int num = 0;
        for(int i = 0; i < str.length(); ++i)
        {
            num += (str.charAt(str.length() - 1 - i) - '0') * tens;
            tens *= 10;
        }

        return num;
    }

    public int addStrings(String str1, String str2) {
        return stringToInt(str1) + stringToInt(str2);
    }

    public static void main(String [] args) {
        StringToInt s = new StringToInt();
        System.out.println(s.addStrings("145", "23"));
    }
}

Conner on Oct 16, 2014
0

@Conner

What if the strings are 1000 characters long? does your int tens and int num variables support that?

Gabriel on Oct 17, 2014

Add Answers or Comments

To comment on this, Sign In or Sign Up.