2011-07-05 113 views

回答

7
def multiply(a, b):                                        
    if (a == 1): 
     return b 
    elif (a == 0): 
     return 0 
    elif (a < 0): 
     return -multiply(-a, b) 
    else: 
     return b + multiply(a - 1, b) 
+0

問題是關於模擬乘法而不使用乘法函數...您可能只能使用加法.. – KawaiKx

+0

這是一個遞歸函數。如果你仔細查看代碼,你會發現它只是做了添加(並且反覆調用自己)。 –

+0

我認爲他的意思是你的' - '符號的乘法 – jemmanuel

1

一些僞代碼:

function multiply(x, y) 
    if abs(x) = x and abs(y) = y or abs(x) <> x and abs(y) <> y then sign = 'plus' 
    if abs(x) = x and abs(y) <> y or abs(x) <> x and abs(y) = y then sign = 'minus' 

res = 0 
for i = 0 to abs(y) 
    res = res + abs(x) 
end 

if sign = 'plus' return res 
    else return -1 * res 

end function 
+0

這是一個非常簡單的解決方案..匹配我的解決方案..非常簡單 – KawaiKx

+1

根據KISS原則(Keep It Stupid Simple):)) –

1
val:= 0 
bothNegative:=false 

if(input1 < 0) && if(input2 < 0) 
    bothNegative=true 
if(bothNegative) 
    smaller_number:=absolute_value_of(smaller_number) 
for [i:=absolute_value_of(bigger_number);i!=0;i--] 
do val+=smaller_number 

return val; 
0
mul(a,b) 
    { 
    sign1=sign2=1; 
    if(a==0 || b==0) 
return 0; 
if(a<0){ 
    sign1=-1; 
    a=-a; 
    } 
    if(b<0){ 
    sign2=-1; 
    b=-b; 
    } 
    s=a; 
    for(i=1;i<b;i++) 
    s+=a; 
    if(sign1==sign2) 
    return s; 
    else 
    return -s; 
    } 
0

這個怎麼樣爲整數:

int multiply(int a, int b) 
{ 
    int product = 0; 
    int i; 
    if (b > 0) 
    { 
     for(i = 0; i < b ; i++) 
     { 
      product += a; 
     } 
    } 
    else 
    { 
     for(i = 0; i > b ; i--) 
     { 
      product -= a; 
     } 
    } 

    return product; 
}