位运算相比于直接进行加减乘除的运算具有高度的时间复杂度优势,下面对位运算实现一些操作做一些整理记录
首先打印一个int的二进制表示的方法
public static void print(int num) {
for (int i = 31; i >= 0; i--) {
System.out.print((num & (1 << i)) == 0 ? "0" : "1");
}
System.out.println();
}
然后关于int整形明确一点 第一位为符号位 0表示正 1表示负
System.out.println(Integer.MIN_VALUE); //-2147483648
System.out.println(Integer.MAX_VALUE); //2147483647
System.out.println(~Integer.MAX_VALUE+1); //-2147483647 取负数
System.out.println(~Integer.MIN_VALUE+1); //-2147483648 取负数(唯一不符合 ~num+1 实现取负数的值)
这样的设计是因为对二进制计算机而言可以大幅提升效率
1.位运算实现乘除2的整数倍
num = num << 1; //*2
num = num << x; //*2的x次方
num = num >> 1; // /2
num = num >> x; // /2的x次方
2.异或运算 ^ 称之为 无进位想加
与运算 & 并左移1位 称之为 取进位的结果
3.位运算实现 + - 查询
public static class BitMap {
private long[] bits;
public BitMap(int max) {
bits = new long[(max + 64) >> 6];
}
public void add(int num) {
bits[num >> 6] |= (1 << (num & 63));
}
public void delete(int num) {
bits[num >> 6] &= ~(1 << (num & 63));
}
public boolean contains(int num) {
return (bits[num >> 6] & (1 << (num & 63))) != 0;
}
}
4.位运算实现+ - * /
public static int add(int a, int b) {
int sum = a;
while (b != 0) {
sum = a ^ b;
b = (a & b) << 1;
a = sum;
}
return sum;
}
public static int negNum(int n) {
return add(~n, 1);
}
public static int minus(int a, int b) {
return add(a, negNum(b));
}
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 = 30; i >= 0; i = minus(i, 1)) {
if ((x >> i) >= y) {
res |= (1 << i);
x = minus(x, y << i);
}
}
return isNeg(a) ^ isNeg(b) ? negNum(res) : res;
}
public static int divide(int a, int b) {
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) {
if (b == negNum(1)) {
return Integer.MAX_VALUE;
} else {
int c = div(add(a, 1), b);
return add(c, div(minus(a, multi(c, b)), b));
}
} else {
return div(a, b);
}
}