/**
* 位运算骚操作
*/
public class BitOperation {
public static void main(String[] args) {
//bitOpeExchangeNum();
int[] arr = {1, 1, 1, 1, 2, 2, 2};
//extractEvenOdds(arr);
extractTheRightBit1(248);
int[] ftn = {3, 1, 1, 1, 2, 3, 3, 4, 4, 2};
findTwoNumber(ftn);
findBit1(234); // 二进制有5个1
}
/*找出二进制中1出现的次数*/
public static void findBit1(int num){
int count = 0;
while (num != 0){
int hook = num & (~num + 1);
count ++;
num ^= hook;
}
System.out.println(count);
}
/*数组中两种数出现了奇数次,其它数出现了偶数次*/
public static void findTwoNumber(int[] arr) {
int eor = 0;
for (int value : arr) {
eor ^= value;
}
//a != b 必然在最右有1
int hook = eor & (~eor + 1);
int only = 0;
for (int value : arr) {
if((value & hook) == 0){
only ^= value;
}
}
System.out.println(only + " " + (eor^only));
}
/*提取一个数二进制的最右侧的1*/
public static void extractTheRightBit1(int num) {
int h = ~num + 1;
num = num & h;
System.out.println(num);
}
/*数组中一种数出现奇数次其它出现偶数次,怎么找出来*/
public static void extractEvenOdds(int[] arr) {
int eor = arr[0];
for (int i = 1; i < arr.length; i++) {
eor ^= arr[i];
}
System.out.println(eor);
}
public static void bitOpeExchangeNum() {
int i = 10, j = 20;
i = i ^ j;
j = i ^ j;
i = i ^ j;
System.out.println(i);
System.out.println(j);
}
}
左老师的算法课程的学习记录