位运算的骚操作

/**
 * 位运算骚操作
 */
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);
    }
}

 左老师的算法课程的学习记录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值