在C#中,是否可以在不使用if、else、循环等结构的情况下对两个32位整数进行求和?
也就是说,是否可以仅使用按位操作OR(|
)、AND(&
)、XOR(^
)、NOT(!
)、左移(<<
)和右移(>>
)来实现?
在C#中,是否可以在不使用if、else、循环等结构的情况下对两个32位整数进行求和?
也就是说,是否可以仅使用按位操作OR(|
)、AND(&
)、XOR(^
)、NOT(!
)、左移(<<
)和右移(>>
)来实现?
这里是一个供您娱乐的示例
unsigned int myAdd(unsigned int a, unsigned int b)
{
unsigned int carry = a & b;
unsigned int result = a ^ b;
while(carry != 0)
{
unsigned int shiftedcarry = carry << 1;
carry = result & shiftedcarry;
result ^= shiftedcarry;
}
return result;
}
循环可以展开。它执行的次数取决于操作数中设置的位数,但从不超过 unsigned int
的宽度。一旦 carry
变为 0
,下一次迭代就不会改变任何东西。
试一下这个:
private int add(int a, int b) {
if(b == 0)
return a;
return add( a ^ b, (a & b) << 1);
}
编辑:
更正了 if
语句
if
语句改为 if ((a & b) == 0) return (a ^ b);
如何?这将减少一个额外的递归调用。 - rootkea想想加法是如何逐位进行的。将值移位以依次获取每个操作数的每个位,然后查看两个位的四个可能值,并计算结果位应该是什么以及是否存在进位位需要考虑。然后使用位运算符计算结果和进位。
static int binaryadd(int x, int y)
{
while (x != 0)
{
int c = y & x;
y = y ^ x;
x = c << 1;
}
return y;
}
public static int getSum(int p, int q)
{
int carry=0, result =0;
for(int i=0; i<32; i++)
{
int n1 = (p & (1<<(i)))>>(i); //find the nth bit of p
int n2 = (q & (1<<(i)))>>(i); //find the nth bit of q
int s = n1 ^ n2 ^ carry; //sum of bits
carry = (carry==0) ? (n1&n2): (n1 | n2); //calculate the carry for next step
result = result | (s<<(i)); //calculate resultant bit
}
return result;
}
i++
不是加法,它表示将变量 i 的值加 1。;) - Qantas 94 Heavypublic int getSum(int a, int b) {
while(b!=0){
int temp=a;
a=a^b;
b=(temp&b)<<1;
}
return a;
}
int Add(int a, int b)
{
int result = 0,
// carry now contains common set bits of "a" and "b"
carry = a & b;
if (Convert.ToBoolean(carry))
{
// Sum of bits of "a" and "b" where at least one
// of the bits is not set
result = a ^ b;
// carry is shifted by one so that adding it
// to "a" gives the required sum
carry = carry << 1;
result = add(carry, result);
}
else
{
result = a ^ b;
}
return result;
}
两个二进制位的和可以使用异或运算符^
来计算,进位位可以通过使用与运算符&
来获得。
如果提供的a
和b
在同一位置上没有设置位,则使用^
运算符可以得到a
和b
的和。
int b = 25;
for (int t = 128; t > 0; t = t / 2)
{
if ((b & t) != 0) Console.Write("1 ");
if ((b & t) == 0) Console.Write("0 ");
}
Console.WriteLine();
//b = (sbyte)~b;
int e = 22;
for (int t = 128; t > 0; t = t / 2)
{
if ((e & t) != 0) Console.Write("1 ");
if ((e & t) == 0) Console.Write("0 ");
}
Console.WriteLine();
int c = b | e;
for (int t = 128; t > 0; t = t / 2)
{
if ((c & t) != 0) Console.Write("1 ");
if ((c & t) == 0) Console.Write("0 ");
}