1 Byte = 8 bit
1 bit is 1 or 0.
- Add
/*
**
**
*/
int Add(int a, int b){
if(b == 0) return a;
int sum = a ^ b; // Get the addition without carry
int carry = (a & b) << 1; //Get the carry
return Add(sum, carry);
}
//bug1 (a & b) << 1 need ()
int Add(int a, int b){
if(b == 0) return a;
else if(a == 0) return b;
int sum = a ^ b;
int carry = (a & b) <<1;
while(carry > 0){
sum = a ^ b ;
carry = (a & b) << 1;
a = sum;
b = carry;
}
return sum;
}
- Subtraction
// nums1 - nums2 = nums1 + (-nums2)
int Substract(int num1, int num2){
int subtractor = add(~num2, 1); // 取反加1 得补码
return Add(num1, subtractor);
} - Multiplication
// basic idea is a added b times.
//Bug here: use n1 as sum. n1 = Add(n1, n1)
int Multiply(int a, int b){
int n1 = a < 0? Add(~a, 1): a;
int n2 = b < 0 ? Add(~b, 1):b;
int sum = 0;
while(n2 >0){
sum = Add(sum, n1);
n2 = Add(n2, -1);
}
//sign of the result
if((a ^ b)< 0 ){ // 只考虑最高位,a,b 异号, 异或后最高位为1, 同号为0
sum = Add(~sum, 1);
}
return sum;
}
- Division
/// <summary>
/// Use dividend minus the divisor
/// if divident absolute value is much larger than absolute value of divisor
/// it will be very slow.
/// </summary>
public static int DivideBit(int a, int b)
{
int divident = a > 0 ? a : Add(~a, 1);
int divisor = b > 0 ? b : Add(~b, 1);
int quotient = 0;
int remainder = 0;
while (divident >= divisor)
{
quotient = Add(quotient, 1);
divident = Substract(divident, divisor);
}
if ((a ^ b) < 0)
{
quotient = Add(~quotient, 1);
}
remainder = b > 0 ? divident : Add(~divident, 1);
return quotient;
}
public static int DivideBit2(int a, int b)
{
int dividend = a > 0 ? a : Add(~a, 1);
int divisor = b > 0 ? b : Add(~b, 1);
int quotient = 0;
int remainder = 0;
for (int i = 31; i >= 0; i--)
{
//比较dividend是否大于divisor的(1<<i)次方,不要将dividend与(divisor<<i)比较,而是用(dividend>>i)与divisor比较,
//效果一样,但是可以避免因(divisor<<i)操作可能导致的溢出,如果溢出则会可能dividend本身小于divisor,但是溢出导致dividend大于divisor
if ((dividend >> i) >= divisor)
{
quotient = Add(quotient, 1 << i);
dividend = Substract(dividend, divisor << i);
}
}
if ((a ^ b) < 0)
{
quotient = Add(~quotient, 1);
}
remainder = b > 0 ? dividend : Add(~dividend, 1);
return quotient;
}