逻辑运算符
六个运算符:&与(And)、|或(Or)、!非(Not)、^异或、&&短路与、||短路或
1.&运算规则:
true&true=true true&false=false false&true=false false&false=false
见false为false。
2.|运算规则:
true|true=true true|false=true false|true=true false|false=false
见true为true。
3.!运算规则:
!true=false !false=true
非否即是,非是即否。
4.^运算规则:
true^true=false true^false=true false^true=true false^false=false
相同则为false,不同则为true。
5.&&运算规则:
对于&&而言,如果前边的表达式的结果为false,则后边的表达式就不再运算。
6.||运算规则:
对于||而言,如果前边的表达式的结果为true,则后边的表达式就不再运算。
注意:短路特性可以提高代码的运算速度。
位运算符
7个运算符号:
&(与)、|(或)、 ^(异或)、<<(左移)、>>(右移)、>>>(无符号右移)、~(取反)
注意:位运算针对的是整数,运算的是数据的补码
可以利用&来判断是否是奇偶数。
1.原、反、补码
数据在计算机中是以补码形式来存储的。最高位是一个符号位:如果是正数,最高位为0,如果是负数,最高位为1。对于正数而言,原反补三码一致。负数的反码是在原码的基础上,最高位不变,其余位0变1,1变0,负数的补码是在反码的基础上+1。
6- 00000000 00000000 00000000 00000110—原码/反码/补码
-6 - 10000000 00000000 00000000 00000110—原码
11111111 11111111 11111111 11111001—反码
11111111 11111111 11111111 11111010—补码
11111111 11111111 11111111 11101101—补码
11111111 11111111 11111111 11101100—反码
10000000 00000000 00000000 00010011—原码— -19
与或非运算规则。
常见运用:
1、奇数^偶数=奇数
2、a ^ b ^ b = a; b ^ b ^ a = a,a和b的地址不同的时候可以拿来交换。
3、提取一个二进制位最右侧的1:
- 借助一下题目:
给你一个整数数组,里面只有两个数是出现奇数次,其余均出现偶数次,提取出这两个给数字
public static int[] function(int[] arr)
{
int eor1 = 0, eor2 = 0;
for (int i:arr)
eor1 ^= i;
int rightOne = eor1 & (~eor1 + 1);
for (int i:arr)
{
if((i & rightOne) == 0) //或者rightOne也可以,因为结果只可能是0或者rightOne
eor2^=i;
}
return new int[]{eor1 ^ eor2,eor2};
}
4、求二进制中1的个数
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res = 0;
for(int i = 1; i <= 32 ; i++){
if((n&1) == 1){
res++;
}
n = n >> 1;
}
return res;
}
}