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 + 1Tricks
http://www.jiuzhang.com/tutorial/bit-manipulation/84
n & (n-1)remove last1in binary
https://leetcode.com/problems/power-of-two/description/ https://leetcode.com/problems/number-of-1-bits/description/
determine odd/even:
n % 2orn & 1,n & 1is better, unsigned integer can be larger than Integer.MAX_VALUEget last bit:
x & -x
+, -, *, / operations
+, -, *, / operationsLast updated
Was this helpful?