目录
2、在hashmap中用到 num % 2^n <==> num & (2^n-1)
1、打印一个整型的32位二进制
public void print(int num){
for (int i = 31; i >= 0 ; i--) {
System.out.print( ( num & (1<<i) ) == 0 ? 0 : 1 );
}
}
2、在hashmap中用到 num % 2^n <==> num & (2^n-1)
举例说明:127% 64
127: 0000 0000 0111 1111
64 : 0000 0000 0100 0000
127对64取模结果肯定为0~63,也就是取127的第0位到第5位:0000 0000 0011 1111,而 127 & 63 恰好是取127的第0位到第5位。
127: 0000 0000 0111 1111
63 : 0000 0000 0011 1111
所以这两种写法是等价的,但是与运算的速度要快很多。
3、位运算实现+ - * /
public class Solution{
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;
}
//complement是补码
public static int complement(int n) {
return add(~n, 1);
}
public static int minus(int a, int b) {
return add(a, complement(b));
}
public static int multiply(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) ? complement(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, multiply(c, b)), b));
}
} else {
return div(a, b);
}
}
}