LeetCode Day.06 关于二进制与位运算的总结

7 篇文章 0 订阅
6 篇文章 0 订阅

background

之前一段时间遇到了Leetcode中一些比较简单的题目,但是有一些的最优解决方案是通过位运算实现的,即简洁又高效。本节整理下c++中关于二进制以及位运算的基本知识,以及在算法中的相关应用。

Menu

  1. (Share) A summary: how to use bit manipulation to solve problems easily and efficiently

(Share) A summary: how to use bit manipulation to solve problems easily and efficiently

首先翻译一篇在Leetcode中讲解位运算在算法中的应用的文章
原链接:A summary: how to use bit manipulation to solve problems easily and efficiently

Wiki

Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a word. Computer programming tasks that require bit manipulation include low-level device control, error detection and correction algorithms, data compression, encryption algorithms, and optimization. For most other tasks, modern programming languages allow the programmer to work directly with abstractions instead of bits that represent those abstractions. Source code that does bit manipulation makes use of the bitwise operations: AND, OR, XOR, NOT, and bit shifts.

Bit manipulation, in some cases, can obviate or reduce the need to loop over a data structure and can give many-fold speed ups, as bit manipulations are processed in parallel, but the code can become more difficult to write and maintain.

位运算是对于 位(bit) 或者 其他一段比一个字(word)短的数据 进行的算法操作。电脑程序中需要位运算的任务包括:低位设备控制器、误差检测与矫正、数据压缩、加密算法和最优化等。
对于大多数任务来说,现代的程序语言允许编程人员直接使用抽象的接口而非位运算。源代码通过使用位运算符:AND,OR,XOR,NOT和 移位运算符 进行位运算。在某些情况下,由于位运算是并行处理的,它可以减少或消除给定数据结构的循环次数,并提供多重加速。但是代码会变得更难编写和理解。

Details

Basics

At the heart of bit manipulation are the bit-wise operators & (and), | (or), ~ (not) and ^ (exclusive-or, xor) and shift operators a << b and a >> b.

位运算的核心是位操作符 &(与 and),|(或 or),~(非 not),^(异或 xor),移位运算 a<<b 和 a>>b

There is no boolean operator counterpart to bitwise exclusive-or, but there is a simple explanation. The exclusive-or operation takes two inputs and returns a 1 if either one or the other of the inputs is a 1, but not if both are. That is, if both inputs are 1 or both inputs are 0, it returns 0. Bitwise exclusive-or, with the operator of a caret, ^, performs the exclusive-or operation on each pair of bits. Exclusive-or is commonly abbreviated XOR.

没有对应于位异或的boolean运算符,但有一个简单的解释。exclusive or操作接受两个输入,如果其中一个输入或另一个输入为1,则返回1。也就是说,如果两个输入都是1或两个输入都是0,则返回0。异或(^)对每对位执行exclusive-or操作。exclusive or通常缩写为xor。

  • Set union A | B
  • Set intersection A & B
  • Set subtraction A & ~B
  • Set negation ALL_BITS ^ A or ~A
  • Set bit A |= 1 << bit
  • Clear bit A &= ~(1 << bit)
  • Test bit (A & 1 << bit) != 0
  • Extract last bit A&-A or A&~(A-1) or x^(x&(x-1))
  • Remove last bit A&(A-1)
  • Get all 1-bits ~0

Example

  • 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 2
    是否为2的指数
bool isPowerOfTwo(int n) {
    return !(n&(n-1)) && (n&0xFFFFFFFF);
}
  • is power of 4 (actually map-checking, iterative and recursive methods can do the same)
    是否为4的指数
bool isPowerOfTwo(int n) {
    return !(n&(n-1)) && (n&0x55555555);
}
  • Sum of Two Integers
int Sum(int a,int b) {
	int tmp;
	while(b){
		tmp = a ^ b;
		b = (a & b) << 1;
		a = tmp;
	}
	return a;
}
  • Sum of Two Integer(plus)
int Sum(int a,int b) {
	int tmp;
	while(b){
		tmp = a & b;
		a = a ^ b;
		b = (tmp & 0xFFFFFFFF) << 1;
	}
	return a;
}
  • 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();
}

明天再写

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值