Interview Question

• 0

Comment hidden because of low score. Click to expand.
0
of 0 vote

Does the order matter? so 6+7 is different from 7+6?

Comment hidden because of low score. Click to expand.
0
of 0 vote

no

Comment hidden because of low score. Click to expand.
0
of 0 vote

<pre lang="" line="1" title="CodeMonkey26644" class="run-this">static vector<int> vectornum;
int findAllSumNum(int num, int n, int znum)
{
if (n <= 0)
return 0;
else if (1 == n)
{
int size = vectornum.size();
for (int i = 0;i < size-1;i++)
printf("%d + ",vectornum[i]);
printf("%d = %d\n",vectornum[size-1],znum);
}
else if (2 == n)
{
int end = num&1 ? (num>>1)+1 : (num>>1);
for (int i = 1;i < end;i++)
{
vectornum.push_back(i);
vectornum.push_back(num-i);
findAllSumNum(0,1,znum);
vectornum.pop_back();
vectornum.pop_back();
}
}
else
{
int begin = num&1 ? (num>>1)+1 : (num>>1);
for (int i = begin;i < num-2;i++)
{
vectornum.push_back(i);
findAllSumNum(num-i,n-1,znum);
vectornum.pop_back();
}
}
return 0;
}

</pre><pre title="CodeMonkey26644" input="yes">
</pre>

Comment hidden because of low score. Click to expand.
0

Can you explain the code please?

Comment hidden because of low score. Click to expand.
0

we start simple
if n = 2 num = (num-1)+1 ,(num-2)+2,... (num-(num/2-1))+(num/2-1)
we say that f(num, 2)
if n = 3 num = (num-1)+f(1,2),(num-2)+f(2,2),(num-num/2)+f(num/2,2)
we say that f(num, 3)
if n = 4 num = (num-1)+f(1,3),....
we say that f(num, 4)
if n = m num = (num-1)+f(1,m-1),...

Comment hidden because of low score. Click to expand.
0
of 0 vote

Question asks for only combinations of single digit numbers that add up to the sum. So (num-1)+1 will not work if num > 10.

Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>

using namespace std;

void print(int arr[], int length)
{
for(int i = 0; i < length; i++)
cout << arr[i];
cout << endl;
}

void Recurse(int sum , int n, int ind, int arr[])
{
if(n == 1 && (sum > 0 && sum < 10))
{
arr[ind] = sum;
print(arr, ind + 1);
return;
} else if(n == 1)
return;

for(int i = 0; i < 10; i++)
{
arr[ind] = i;
Recurse(sum - i, n - 1, ind + 1, arr);
}
return;
}

int main(void)
{
int sum = 13;
int n = 2;
int arr[2];
Recurse(sum, n, 0, arr);
return 0;
}

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.