Bit Manipulation
Bit Manipulation
- Basic operation
- Basic use case
- Interview Questions
How Integer is stored in Memory
Integer -> 4 bytes -> 32 bits
Long -> 8 bytes -> 64 bits
Boolean/Char -> 1 byte
Two's complement
Basic Operation
- Bitwise NOT
- ~0111 = 1000
- Bitwise OR
- 0101 | 1010 = 1111
- Bitwise AND
- 0101 & 1100 = 0100
- Bitwise XOR
- 0101 ^ 0011 = 0110
Basic Operation
- Bitwise SHIFT
- 0001 << 3 = 1000
- 1100 >> 1 = 1110 -- arithmetic
- 1100 >>> 1 = 0110 -- logical
Basic use case (Tricks)
- Even & Odd
- n & 1 == 1 ? Odd : Even
- Double
- a / 2 = a >> 1;
- a * (2^m) = a << m;
- Negative number
- a = 101101100
- -a = 010010011 + 1 = 010010100
- Bit NOT on every bit and then plus 1.
Basic use case (Tricks)
- Specific bit operation
- Get kth bit: (a >> k) & 1
- Set kth bit 0: a = a & ~(1 << k)
- Set kth bit 1: a = a | (1 << k)
Basic use case (Tricks)
- XOR
- a ^ a = 0
- a ^ 0 = a
Interview Questions
- Bit operation
- Single Number
- Number of 1 Bits
- Reverse Bits
- Reduce storage & improve efficiency
- Combination
Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
def singleNumber(self, A: List[int]) -> int:
for i in range(1, len(A)):
A[i] ^= A[i-1]
return A[-1]Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ’1' bits it has. (also known as the Hamming weight)
def hammingWeight(self, n: int) -> int:
result = 0
for i in range(32):
result += n & 1
n >>= 1
return resultGiven an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.
Input: nums = [3,10,5,25,2,8]
Output: 28
Explanation: The maximum result is 5 XOR 25 = 28.
n.
class Trie:
def __init__(self):
self.children = {}
class Solution:
def findMaximumXOR(self, nums: List[int]) -> int:
self.root = Trie()
for n in nums:
self.insert(n, self.root)
res = 0
for n in nums:
res = max(res, self.search(n, self.root))
return res
def insert(self, n, root):
for i in range(30, -1, -1):
cur = (n >> i) & 1
if cur not in root.children:
root.children[cur] = Trie()
root = root.children[cur]
def search(self, n, root):
pre = 0
for i in range(30, -1, -1):
cur = (n >> i) & 1
wanted = (1 - cur)
if wanted in root.children:
root = root.children[wanted]
pre += (1 << i)
else:
root = root.children[cur]
return pre[GoValley-Jo] Bit Manipulation 12
By ZhiTongGuiGu
[GoValley-Jo] Bit Manipulation 12
- 37