I saw in one of the sites an interview question in C, which you are asked to write a function which get 2 integers, num and times, and multiple them without using the * operator, meaning using mainly shift left and right. I came up with a working answer (unless anyone finds a bug), but does anyone has a better way solving it in better time or memory consumption?
here is what I wrote:
#include <stdio.h>
int multiply_with_shift (int num, int times)
{
int cnt=0;
int org_times=times;
if((num & times)==0)
return 0;
else
{
while(times >1)
{
times= times >> 1;
cnt++;
}
int val= 1;
val= val <<cnt;
int sub= org_times-val;
int res= num << cnt;
for( int i=0 ; i < sub; i++)
{
res+=num;
}
return res;
}
}
void main()
{
int tmp;
tmp=multiply_with_shift(5,15);
printf(" the answer is : %d \n", tmp);
printf("\n");
}
?