Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return the result of sum of character arrays

Recently in an interview i was asked a question to write a function which takes two character arrays(integers) as input and returns the output character array.

Function Signature:

char* find_sum(char* a, char* b)

How would one approach this?

Example scenario:

find_sum("12345","32142") = "44487"

Note:

The number of digits can be many(1-100).

like image 730
josh Avatar asked Sep 21 '10 06:09

josh


People also ask

How to find the sum of ASCII values in a character array?

Write a C++ Program to find the Sum of ASCII values in a Character Array with an example. In this C++ code, we allow the user to enter a character array and used for loop (for (i = 0; name [i] != ‘\0’; i++) ) to iterate values from 0 to character array length.

How to sum elements of an array in STL?

Sum of given array is 34. Time Complexity: O(n) Auxiliary Space: O(1) Another Method: Using STL Calling inbuilt function for sum of elements of an array in STL. accumulate(first, last, sum); first, last : first and last elements of range whose elements are to be added sum : initial value of the sum. This function returns the array sum.

How to calculate the sum of the alphabetical values of a string?

Approach: 1 Find the given string in the array and store the position of the string. 2 Then calculate the sum of the alphabetical values of the given string. 3 Multiply the position of the string in the given array with the value calculated in the previous step and print the... More ...

How to return an array with the index function in Excel?

Sum/ Return an Array with the Index Function 1 We will click on Cell D4 2 We will input the formula into Cell D4: =SUM (INDEX (B4:B11,N (IF (1, {1,6,8})))) 3 We will press the enter key to get the result


3 Answers

u can add huge numbers using the char array approach. however you need to delete the char* after using it every time or use some smart pointer.

 char* find_sum(char* a, char* b) {
    int lenA = strlen(a), lenB = strlen(b);
    int max = lenA > lenB ? lenA : lenB; // Get the max for allocation
    char* res = (char*)malloc (max+2);
    memset(res, '0', max +1);      // set the result to all zeros
    res[max+1] = '\0';
    int i=lenA - 1, j = lenB - 1, k = max;
    for (; i >= 0 || j >=0; --i, --j, --k) {
            int sum = 0;
            if (i >= 0 && j>=0)
                    sum = a[i] - '0' + b[j] - '0' + res[k] - '0' ;  // add using carry
            else if (j >= 0)
                    sum =  b[j] - '0' + res[k] - '0' ;     // add the carry with remaining
            else if (i >= 0)
                    sum =  a[i] - '0' + res[k] - '0' ;
            res[k] = sum % 10 + '0';
            res[k-1] = sum / 10 + '0';
    }
    return res;
 }

 int main() {
    printf (" sum = %s ", find_sum("12345432409240242342342342234234234", "9934563424242424242423442424234"));
    return 0;
 }

Note: The precondition for the function is the input char arrays should contain only numbers.

like image 78
aeh Avatar answered Oct 06 '22 01:10

aeh


The most obvious answer is internally to use something like atoi and sprintf to convert the numbers to integers, do the sum and return the response as a char* However the important thing here is not what the interviewer is asking but why.

In my experience, the interviewer is probably not wanting you to write a hum-dinger of a solution that covers all angles. What they most likely want to get to is what the most common approach would be, and what are the likely limitations of such a function. I.e.:

  1. What happens if your input numbers aren't integers? (e.g. 13.245, 2.3E+7)

  2. What happens if your 'numbers' aren't numbers at all?

  3. What happens if your input integers are really big? (i.e. ~2^31)

  4. How could you detect an error and how would you report it.

  5. How would you allocate memory for the resultant string?

  6. What would the memory allocation imply for the calling code?

  7. What is the efficiency of the function and how could you make it more efficient?

In this way, the interviewer wants to probe your experience of critiquing approaches to problem solving. Naturally, there are many ways of solving this problem. Some of the approaches have side-effects but in certain contexts, these side effects (i.e. integer overflow) may not be greatly important.

Coding is often a trade off between a comprehensive solution and what can be produced quickly (and therefore less expensively) These questions allow the interviewer to get a feel for your understanding of quality - that is, can you design something that is fit for purpose, robust and yet does not take too long to put together - and also your experience of having to identify / resolve common bugs.

like image 32
Component 10 Avatar answered Oct 05 '22 23:10

Component 10


You did not mention anything about not using any external command.

We can do this easily on machines that have the bc command. You can add any number of digits:

$ echo "99999999999999999999999999999999+1" | bc
100000000000000000000000000000000
$ 

We call this bc from the C program. We need to construct the right command line as

echo "n1+n2" | bc

and then use popen to read its result. Below is the function to do that. The code lacks many error checking.

char* find_sum(char* a, char* b) {

        int l1 = strlen(a),l2 = strlen(b);
        int cmdLen = l1 + l2 + 30; // 30 to accomodate echo,bc and stuff.

        char *cmd = malloc(cmdLen);    
        snprintf(cmd,cmdLen,"echo \"%s+%s\"|bc",a,b);

        FILE *fp = popen(cmd, "r");

        int max = (l1 > l2) ? l1:l2;
        max += 2; // one for additional digit, one for null.
        char *result = malloc(max);

        fgets(result, max, fp);
        return result;
}

Working link

like image 30
codaddict Avatar answered Oct 05 '22 23:10

codaddict