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;
}
Сумма двух битов может быть выполнена с помощью оператора XOR ^
, а бит переноса может быть получен с помощью оператора AND &
.Если a
и b
не имеют установленных битов в одной и той же позиции, то использование оператора ^
дает сумму a
и b
.
Комментарии от geeksforgeeks