位图
1 位图的功能
可以做出一个集合,如果最大值很确定,可以用位图来实现收集数字,并且告诉你这个数字存在还是不存在
2 位图的好处
极大的压缩空间
3 位图的实现
public class Code02_BitMap2 {
public static class BitMap {
private long[] bits;
public BitMap(int max) {
bits = new long[(max + 64) >> 6];
}
public void add(int num) {
// num >> 6 -> num / 64 -> 哪个整数
// num & 63 -> num % 64 -> 哪个位置
// |=将 1左移num位,然后和bits[num >> 6]进行或操作;
bits[num >> 6] |= (1L << (num & 63));
}
public void delete(int num) {
// num >> 6 -> num / 64 -> 哪个整数
// num & 63 -> num % 64 -> 哪个位置
// ~ 将1左移num位,然后和bits[num >> 6]进行与操作;
bits[num >> 6] &= ~(1L << (num & 63));
}
public boolean contains(int num) {
return (bits[num >> 6] & (1L << (num & 63))) != 0;
}
public static void main(String[] args) {
System.out.println("测试开始! ");
int max = 10000;
BitMap bitMap = new BitMap(max);
HashSet<Integer> set = new HashSet<>();
int testTime = 10000000;
for (int i = 0; i < testTime; i++) {
int num = (int)(Math.random() * (max + 1));
double decide = Math.random();
if(decide < 0.333){
bitMap.add(num);
set.add(num);
}else if(decide < 0.666) {
bitMap.delete(num);
set.remove(num);
}else {
if(bitMap.contains(num) != set.contains(num)){
System.out.println("Oops!");
break;
}
}
}
for (int num = 0; num <= max; num++) {
if(bitMap.contains(num) != set.contains(num)){
System.out.println("Oops!");
}
}
System.out.println("测试结束!");
}
}
}
4 用位运算实现+ - * /
1 加法
2 减法
3 乘法
4 除法
public class Code03_BitAddMinusMultiDiv {
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 {
// a / b
// (a + 1) / b == c
// a - (b * c) = d
// d / b = e
// c + e
int ans = div(add(a,1),b);
return add(ans,div(minus(a,multi(ans,b)),b));
}
}else {
return div(a,b);
}
}
}