Amazon Interview Question
Software Engineer / Developers{
private static int recMultiplyHelper(int x, int y)
{
if (y == 1)
return x;
else
return x + recMultiply(x, y - 1);
}
public static int Multiply(int x, int y)
{
if (x == 0 || y == 0)
return 0;
bool isAnswerNegative = false;
if (x < 0 && y > 0 || x > 0 && y < 0)
isAnswerNegative = true;
if (x < 0)
{
x = x - x - x;
}
if (y < 0)
{
y = y - y - y;
}
int answer = recMultiplyHelper(x, y);
if (isAnswerNegative)
{
answer = answer - answer - answer;
}
return answer;
}
}
Here is another version
int multiply(int a, int b) {
if (a == 0 || b == 0) {
return 0;
}
a += multiply(a, abs(b) - 1);
return (b < 0) ? -1 * a : a;
}
My Bad... used a multiplication operator.
updated version
int multiply(int a, int b) {
if (a == 0 || b == 0) {
return 0;
}
a += multiply(a, abs(b) - 1);
return (b < 0) ? (0 - a) : a;
}
#include<stdio.h>
- naive October 24, 2009int func(int a,int cnt)
{
int ans=0;
if(cnt==0)
return 0;
ans=a+func(a,--cnt);
return ans;
}
main()
{
int a,b;
scanf("%d%d",&a,&b);
printf("%d\n",func(a,b));
}