位运算 详解 技巧

本文介绍了位运算的各种操作,如并集、交集、差集、取反等,并通过实例展示了位运算在求解问题中的应用,如计算1的个数、判断是否为4的次方数、反转位、求缺失数字等。此外,还讨论了位运算在DNA序列分析、多数元素查找、最大单词长度乘积等问题中的解决方案。
摘要由CSDN通过智能技术生成

原文来源于网络,已经无法考证出处,我将原文进行了一个理解性的翻译和总结:

  • Set union A | B 并集
  • Set intersection A & B 交集
  • Set subtraction A & ~B 求差集
  • Set negation ~A 取反
  • Set bit A |= 1 << bit 将某一位置1
  • Clear bit A &= ~(1 << bit) 将某一位置0
  • Test bit (A & 1 << bit) != 0 测试某一位是否为1
  • Remove last bit A&(A-1) 清除最右边的一个1
  • Extract last bit A&-A or A&~(A-1) or x^(x&(x-1)) 提取出来最右边的一个1
  • Get all 1-bits ~0 拿到所有位全是1的值

Examples

Count the number of ones in the binary representation of the given number 求1的个数

int count_one(int n) {
    while(n) {
        n = n&(n-1);
        count++;
    }
    return count;
}

Is power of four (actually map-checking, iterative and recursive methods can do the same) 求是否是4的次方数

bool isPowerOfFour(int n) {
    return !(n&(n-1)) && (n&0x55555555);
    //check the 1-bit location;
}

^ tricks

Sum of Two Integers

int getSum(int a, int b) {
    return b==0? a:getSum(a^b, (a&b)<<1); //be careful about the terminating condition;
}

Missing Number

Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array. For example, Given nums = [0, 1, 3] return 2. (Of course, you can do this by math.)

int missingNumber(vector<int>& nums) {
    int ret = 0;
    for(int i = 0; i < nums.size(); ++i) {
        ret ^= i;
        ret ^= nums[i];
    }
    return ret^=nums.size();
}

| tricks

Keep as many 1-bits as possible
求<=给定的数的2的幂
Find the largest power of 2 (most significant bit in binary form), which is less than or equal to the given number N.
将连续的两位置1,将连续的四位置1,直到将连续的32位置1。最后结果右移。

long largest_power(long N) {
    //changing all right side bits to 1.
    N = N | (N>>1);
    N = N | (N>>2);
    N = N | (N>>4);
    N = N | (N>>8);
    N = N | (N>>16);
    return (N+1)>>1;
}

Reverse Bits

Reverse bits o

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值