目录
位运算实现加法
位运算实现减法
位运算实现乘法
位运算实现除法
代码示例
PS:用位运算实现的加减乘除,其数据都是整型的(int、char、size_t等)
位运算实现加法
LeetCode_2.两数相加_小白麋鹿的博客-CSDN博客https://yt030917.blog.csdn.net/article/details/129628846
位运算实现减法
减法用加上一个数的相反数来实现
位运算实现乘法
LeetCode_面试题 08.05. 递归乘法_小白麋鹿的博客-CSDN博客https://yt030917.blog.csdn.net/article/details/129918992
位运算实现除法
LeetCode_29. 两数相除_小白麋鹿的博客-CSDN博客https://yt030917.blog.csdn.net/article/details/130753574
代码示例
class Calculate
{
public:
//加法
int add(int num1, int num2)
{
while (num2 != 0)
{
//注意这里强转是为了防止越界
unsigned int tmp = static_cast<unsigned int>(num1 & num2) << 1;
num1 = num1 ^ num2;
num2 = tmp;
}
return num1;
}
//减法
int sub(int num1, int num2)
{
return add(num1, -num2);
}
//乘法
int multiply(int A, int B)
{
int tag = A ^ B;
int product = 0;
A = abs(A);
B = abs(B);
for (int i = 0; A >> i; i++)
{
if ((A >> i & 1) == 1)
product += (long long)B << i;
}
if (tag < 0)
product = -product;
return product;
}
//除法
int divide(int dividend, int divisor)
{
if (dividend == INT_MIN && divisor == INT_MIN)
return 1;
else if (divisor == INT_MIN)
return 0;
if (dividend == INT_MIN)
{
if (divisor == -1)
return INT_MAX;
else if (divisor == 1)
return INT_MIN;
int tmp = div(dividend + 1, divisor);
return tmp + div(dividend - multiply(tmp, divisor), divisor);
}
//以上部分均为处理INT_MIN的特殊情况
return div(dividend, divisor);
}
private:
int div(int dividend, int divisor)
{
int tag = dividend ^ divisor;
dividend = dividend > 0 ? dividend : ~dividend + 1;
divisor = divisor > 0 ? divisor : ~divisor + 1;
int ans = 0;
while (dividend >= divisor)
{
int index = -1;
while (dividend >> ++index >= divisor);
index--;
dividend -= divisor << index;
ans |= 1 << index;
}
if (tag < 0)
ans = -ans;
return ans;
}
};