I am trying to implement multiplication of two numbers without using the *
operator, as a practice for programming interviews. I have written two functions.
1) Using Long Multiplication
static int MultiplyTwoNumbers(int num1,int num2)
{
List<int> leftnumber = new List<int>();
do
{
leftnumber.Add(num1% 10);
num1/= 10;
} while (num1!=0);
List<int> rightnumber = new List<int>();
do
{
rightnumber.Add(num2% 10);
num2/= 10;
} while (num2!= 0);
int result = 0;
int counter = 1;
for (int i = 0; i <leftnumber.Count; i++)
{
int tempresult = 0;
int carry = 0;
int innercounter = counter;
for (int j = 0; j<rightnumber.Count; j++)
{
int tempVal = leftnumber[i] * rightnumber[j];
tempVal += carry;
if (tempVal / 10 != 0)
{
carry = tempVal / 10;
tempVal = tempVal % 10;
}
tempresult = tempresult + (innercounter * tempVal);
innercounter = innercounter * 10;
}
result +=tempresult;
counter = counter * 10;
}
return result;
}
2) using Addition
static int multiplicationUsingAdd(int num1,int num2)
{
int result = 0;
for (int i = 0; i < num2; i++)
{
int temp=result+ num1;
result = temp;
}
return result;
}
Which one is better and how can I improve it ?
*
operator. Presumably you are aiming to avoid that. (If not thenreturn a * b
is the best implementation :) ). \$\endgroup\$num1 * num2
.) \$\endgroup\$*
? \$\endgroup\$int
had to start without havingint
already implemented; they did it somehow. \$\endgroup\$object
count as built-in type for the purpose of this challenge? I don't see a way of creating a C# program without implicitly deriving fromobject
or using other object-derived types, let alone implementing something meaningful. :) \$\endgroup\$