通过位运算实现两个数的加、减、乘、除
2018-01-27 21:59
330 查看
//通过位运算实现两个数的加、减、乘、除
public class BitSuan{
//(1)加法运算
public static int add(int a,int b)
{
int sum=a;
while(b!=0)
{
//a与b无进位相加
sum=a^b;
b=(a&b)<<1;
a=sum;
}
return sum;
}
//负数按位置取反+1
public static int negNum(int n)
{
return add(~n,1);
}
//(2)减法运算
public static int minus(int a,int b)
{
return add(a,negNum(b));
}
//(3)乘法运算
public static int multi(int a, int b) {
int res = 0;
while (b != 0) {
if ((b & 1) != 0) {
res = add(res, a);
}
a <<= 1;
b >>>= 1;
}
return res;
}
//判断是否是负数
public static boolean isNeg(int n) {
return n < 0;
}
public static int div(int a, int b) {
int x = isNeg(a) ? negNum(a) : a;
int y = isNeg(b) ? negNum(b) : b;
int res = 0;
for (int i = 31; i > -1; i = minus(i, 1)) {
if ((x >> i) >= y) {
res |= (1 << i);
x = minus(x, y << i);
}
}
return isNeg(a) ^ isNeg(b) ? negNum(res) : res;
}
//(4)除法运算
public static int divide(int a, int b) {
if (b == 0) {
throw new RuntimeException("divisor is 0");
}
if (a == Integer.MIN_VALUE && b == Integer.MIN_VALUE) {
return 1;
} else if (b == Integer.MIN_VALUE) {
return 0;
} else if (a == Integer.MIN_VALUE) {
int res = div(add(a, 1), b);
return add(res, div(minus(a, multi(res, b)), b));
} else {
return div(a, b);
}
}
public static void main(String[]args)
{
int a=10;
int b=5;
System.out.println(add(a,b));
System.out.println(minus(a,b));
System.out.println(multi(a,b));
System.out.println(divide(a,b));
}
}
相关文章推荐
- 运用异或运算实现两个数不通过中间变量交换值的原理分析
- c# 抽象方法:实现两个数的加、减、乘操作运算
- Python基础语法学习--函数+案例--定义一个函数,实现两个数的四则运算
- 通过位运算实现两个整数加、减、乘、除以及两个变量的交换
- Android studio 通过AIDL来实现加法运算
- 通过CryptoAPI实现MD5运算
- 通过异或运算实现两个变量的交换(不需借助第三个变量)
- 异或运算实现两个数的交换
- C++ 通过main()函数输入参数,实现简单的四则运算
- javascript通过位运算完成两个数的交换
- 异或运算实现两个数的交换
- C语言通过逻辑运算(与或非)实现加法
- 异或运算实现两个数的交换
- Java通过位运算实现10-16进制转换
- 异或运算实现两个数的交换
- 异或运算实现两个数的交换
- 异或运算实现两个数的交换
- 异或运算实现两个数的交换
- 通过位运算实现加减法
- java中通过位运算实现多个状态的判断