0%

神奇的位运算

1.x = x&(x-1)

每一次运算将x的二进制形式中最右边的1(包括1)及其后面置0
应用:统计出x的二进制有多少个1
还可以判断是不是2的n次方(因为如果一个数是2的n次方,那么这个数用二进制表示时其最高位为1,其余位为0。),顺便一提,左移右移也是变换2的n次方的快速方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
public static int func(x) { 
int count = 0;
while(x) {
count ++;
x = x&(x-1);
}
return count;
}

public static boolean func(x) {
if( (x&(x-1)) == 0 ) return true;
else return false;
}

2. x^x = 0、0^x = x

奇偶个数的判断
应用:找出一个数组中只出现一次的数,其他都是两次。

1
2
3
4
5
6
7
public static int singleNumber(int[] nums) {
int result = 0;
for(int i = 0 ; i < nums.length ; i++ ){
result ^= nums[i];
}
return result;
}

**3.x & (-x) **

保留位中最右边 1 ,且将其余的 1 设位 0 的方法。

4.不用“+”,实现“+”

1
2
3
4
5
6
7
8
9
10
11
12
13
public static int getSum(int a, int b) {
while (b != 0) {// 当进位不为0时
// 无进位累加值
int temp = a ^ b;
// 进位值
int carry = (a & b) << 1;

a = temp;
b = carry;
}

return a;
}

5.十进制数判断奇偶性

看其二进制最后一位(当然不用转二进制,x&1即可拿到最后一位),是1为奇数,是0为偶数

------------- Thank you for reading -------------

Title - Artist
0:00