2013-02-13 53 views
-1

我在其中一个站点看到C语言中的一个采访问题,要求您编写一个函数,该函数可以获得2个整数,num和times,并且可以不使用*运算符来对它们进行乘法运算,这意味着主要使用shift左和右。我想出了一个可行的答案(除非有人发现一个bug),但是有没有人有更好的方法来解决它在更好的时间或内存消耗?无整数乘法*

这里是我写的:

#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"); 
} 

+0

可能会在这里得到更好的答案:HTTP ://codereview.stackexchange.com/ – 2013-02-13 14:14:28

+0

我同意fire.eagle。 ((num&times)== 0)'应该是'if((num && times)== 0)' – MByD 2013-02-13 14:15:11

+1

@BinyaminSharet no,它应该是'if((num | times)= = 0)'。 – 2013-02-13 14:22:15

回答

5

这里有一个更简洁,bugfree(我相信)执行,甚至不发生未定义行为:

unsigned mul(unsigned a, unsigned b) 
{ 
    unsigned acc = 0; 
    while (b) { 
     if (b & 1) acc += a; 
     b >>= 1; 
     a <<= 1; 
    } 
    return acc; 
} 

你的代码有几个缺陷:

  1. 可读性,长度等...
  2. if ((num & times) == 0) return 0; - >这将返回0的数字,它们的二进制表示中不共享至少一个共同幂2,即4 * 8 = 0
  3. C中的符号位移位是未定义的行为 - 您需要为此任务使用无符号整数。
+0

'<评论删除>'*此答案下的评论已过时,或纯粹的噪音,并随后被删除。请保持评论的建设性,专业性和主题。* – 2013-02-13 15:34:37

+1

@TimPost OneManCrew指责我一些我没有做的事情。这不公平。 – 2013-02-13 15:42:01

+0

@ H2CO3我真的很喜欢你的答案,找不到一个bug,它处理各种整数,如2^n和零。你有什么想法如何处理有符号整数? – KBE 2013-02-14 13:25:01

0

如果你想要一个有符号整数变型,这会工作:

int mul(int a, int b) 
{ 
    sign = (a^b) >> (sizeof(a) * CHAR_BIT - 1); 
    if (a > 0) 
     a = -a; 
    if (b > 0) 
     b = -b; 
    int acc = 0; 
    while (b) { 
     if (b & 1) acc += a; 
     b >>= 1; 
     a <<= 1; 
    } 
    if (sign) acc = -acc; 
    return acc; 
} 

[感谢H2CO3在另一篇文章的大部分算法实现]

+1

然后它需要返回'int',对吧? :) – 2013-02-13 14:43:31

+0

是的,典型的copy'n'paste错误。 – 2013-02-13 14:46:13

+0

这不起作用。 'a&=〜SIGN'不是在2的补码系统上取绝对值的正确方法。 – interjay 2013-02-13 14:50:30