Yahoo Interview Question
Software Engineer / DevelopersThe obvious solution require O(n) operations. While the following one require O(lgn) operations. It may be the reason they asked the question.
int Sum(int A[], int h, int l)
{
if (h==l) return A[l];
else
{
int m=l+(h-l)/2;
return Sum(A,l,m-1)+Sum(A,m+1,h);
}
}
template <class T>
T sum(T* arr, int num){
T sum=0;
for(int i=0;i<num;i++){
sum += arr[i];
}
return sum;
}
/* program to add two numbers. each number is represented by an int array.
* each element in the array is an number */
#include <iostream>
using namespace std;
void PrintNumber(int* array, int len)
{
for( int i = 0; i<len; i++ )
cout << array[i];
cout << endl;
}
void reverse_array(int* array, int len)
{
int* p = array;
int* q = p + (len-1);
int temp;
while( p < q )
{
temp = *p;
*p = *q;
*q = temp;
p++;
q--;
}
}
void AddNumbers(int* array1, int len1, int* array2, int len2, int** array3, int* len3)
{
int max_len = max(len1, len2);
int* sum_array = (int*)malloc(sizeof(int) * (max_len+1)); //+1 for carry
int i, j;
int k = 0;
int carry = 0;
for( i = len1-1, j = len2-1; i >= 0 && j >=0; i--, j--, k++ )
{
if( (array1[i] + array2[j] + carry) > 9 )
{
sum_array[k] = (array1[i] + array2[j] + carry) % 10;
carry = 1;
}
else
{
sum_array[k] = array1[i] + array2[j] + carry;
carry = 0;
}
}
if( i > 0 )
{
for( ; i >= 0; i--, k++ )
{
if( (array1[i] + carry) > 9 )
{
sum_array[k] = (array1[i] + carry)%10;
carry = 1;
}
else
{
sum_array[k] = array1[i] + carry;
carry = 0;
}
}
}
else if( j > 0 )
{
for( ; j >= 0; j--, k++ )
{
if( (array2[j] + carry) > 9 )
{
sum_array[k] = (array2[j] + carry)%10;
carry = 1;
}
else
{
sum_array[k] = array2[j] + carry;
carry = 0;
}
}
}
sum_array[k] = carry;
reverse_array(sum_array, max_len+1);
*array3 = sum_array;
*len3 = max_len+1;
}
int main()
{
int array1[] = { 1, 1, 1, 1 };
int array2[] = { 9, 9 };
PrintNumber(array1,sizeof(array1)/sizeof(array1[0]));
PrintNumber(array2,sizeof(array2)/sizeof(array2[0]));
int* array3 = NULL;
int len = 0;
AddNumbers(array1, sizeof(array1)/sizeof(array1[0]), array2, sizeof(array2)/sizeof(array2[0]), &array3, &len);
cout << "done with adding numbers" << endl;
PrintNumber(array3,len);
return 0;
}
what kind of numbers, real/integer
- Anonymous December 05, 2009