Bit Manipulation

bit manipulation

Basic Operations

左移操作 A << B
右移操作 A >> B, A >>> B
按位与操作 A & B
按位或操作 A | B
按位非操作 ~A
异或操作 A ^ B, 异或操作也就是不进位加法,比如1 + 1 = 10, 我们只取个位,不要进位的那个1,其他同理。

two's complement: -x = ~x + 1

Tricks

http://www.jiuzhang.com/tutorial/bit-manipulation/84

  • n & (n-1) remove last 1 in binary

https://leetcode.com/problems/power-of-two/description/ https://leetcode.com/problems/number-of-1-bits/description/

  • determine odd/even: n % 2 or n & 1, n & 1 is better, unsigned integer can be larger than Integer.MAX_VALUE

  • get last bit: x & -x

+, -, *, / operations

Last updated

Was this helpful?