[英]Spaces around multiplication and division operators are deleted by IDE, how to keep them?
[英]How to multiple two positive integers without multiplication or division operators or loops
我需要在不使用乘法或除法運算符、任何內置乘法函數或循環的情況下將兩個整數相乘。
我已經設法用循環進行乘法運算,但是如果沒有循環,我不知道如何做到這一點。
這是我的循環解決方案:
Public Double(Double x, Double y)
{
Double Result;
Result =0;
If(x==0 || y==0)
{
Result = 0;
}
else
{
for(int i=0; i<=y; i++)
{
Result = Result + x;
}
}
return Result;
}
您可以在您的功能中執行以下操作
List<int> temp = new List<int>();
temp.AddRange(Enumerable.Repeat(x,y));
var result = test.Sum();
您的 'y' 變量將是整數計數。 但是我不確定你到底在找什么
我需要在不使用乘法或除法運算符、任何內置乘法函數或循環的情況下將兩個整數相乘。
閱讀您的問題的條件,我認為這里的想法是使用更智能的計算方式,例如按位運算。
基於如何使用按位運算符執行乘法中的答案? 對於您的問題,我建議以下解決方案:
public int MultiplyBitwise(int a, int b)
{
int product = 0;
while (b > 0)
{
product += ((b & 1) > 0) ? a : 0;
a <<= 1;
b >>= 1;
}
return product;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.