0% found this document useful (0 votes)
14 views60 pages

Bit Manipulation

The document presents a detailed overview of bit manipulation techniques, focusing on various bitwise operators such as AND, OR, XOR, NOT, NAND, and NOR, along with their applications and properties. It also discusses bit shifting operations and introduces built-in functions for counting bits and determining parity. Additionally, the document outlines a problem-solving approach involving prime numbers and their manipulation based on specific conditions.

Uploaded by

kenma7697
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views60 pages

Bit Manipulation

The document presents a detailed overview of bit manipulation techniques, focusing on various bitwise operators such as AND, OR, XOR, NOT, NAND, and NOR, along with their applications and properties. It also discusses bit shifting operations and introduces built-in functions for counting bits and determining parity. Additionally, the document outlines a problem-solving approach involving prime numbers and their manipulation based on specific conditions.

Uploaded by

kenma7697
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

BIT MANIPULATION

presented by group 1
Ai My, Nguyen Tin, Mai Hien,
Van Tanh, Tan Phuc, Quoc Tien
GROUP MEMBERS

Le Thi Mai Hien Tran Mai Ai My Le Nguyen Tin


GROUP MEMBERS

Phung Van Tanh Nguyen Quoc Tien Nguyen Ly Tan Phuc


PROCESS
1 3

Some
Introduction examples

2 4

Bitwise Pros
Operators &
Cons
INTRODUCTION
Bit Manipulation is a technique used in a variety of

problems to get the solution in an optimized way. It is

all about Bitwise Operators which directly works upon

binary numbers or bits of numbers that help the

implementation fast.
BITWISE OPERATORS
1 2 3

4 5 6
AND
• The result is 1 if both bits are 1;
otherwise, it is 0.
• A&B
• Truth table:
AND
For instance: Check a number if it is
even or odd
AND

Principle:
• If n & 1 == 0, the number is
even (last bit is 0).
• If n & 1 == 1, the number is
odd (last bit is 1).
OR

•The result is 1 if at least one of the two


bits is 1, and 0 only when both are 0.
• A∣B
• Truth table:
XOR
• The result is 1 if the two bits are different,
and 0 if the two bits are the same.
• A⊕B
• Truth table:
XOR
For instance: Given an array of
integers where all elements appear an
even number of times except for one
element that appears an odd number of
times, write a function to find and return
the element that appears an odd
number of times
XOR
Properties of XOR:
a ^ a = 0 (a number XORed with itself equals 0).
a ^ 0 = a (a number XORed with 0 remains
unchanged).
XOR is commutative and associative, meaning
the order of XOR does not affect the result.
When XOR all elements in an array, the elements
that appear twice are eliminated, leaving only a
single element.
Examples: XOR
n=5
12 3 3 1
a=[1,2,3,3,1]
00 xor 01 =
0 xor 1 = 1
1 xor 2 = 01
01 xor 10
3 = 11
3 xor 3 = 11 xor 11
0
0 xor 3 = = 00
00 xor 11
3 = 11
3 xor 1 = 11 xor 01
2 = 10
NOT

• NOT (~):
• Bit inversion (0 to 1, 1 to 0).
• ¬A
NAND
• Invert the result of the AND
operation.
• A NAND B=¬(A&B)
• Truth table:
NOR
• Invert the result of the OR operation.
• A NOR B=¬(A∣B)
• Truth table:
BIT SHIFT
Left Shift (<<) Right Shift (>>)
• a << b: Shifts the bits of a to • a >> b: Shifts the bits of a to
the left by b positions. the right by b positions.
• New bits may appear on the • The bits shifted to the right will
right side of the number, and disappear, and the empty bits on
they will be 0. the left will become 0.
• Example: • Example: 10 >> 2 = 1010 >>
10 << 2 = 1010 << 2 = 2 = 10
101000 •a > > b = a/(2^b)
• a < < b = a*(2^b) • 1 >> k = ½^k
•1 << k = 2^k •K >> 1 = k/2 (integer division)
•K << 1 = k * 2
PRIORITY

Note: When performing


calculations with a << b
where the result may
exceed the int range, you
must perform typecasting
to avoid integer overflow.
Several useful
bit manipulation
tricks
The function The function
__builtin_popcount(x) __builtin_parity(x)

The function The function


__builtin_clz(x) __builtin_ctz(x)
The function
__builtin_popcount(x)
This function counts the number of 1 bits in the
binary representation of the number x.
Time complexity: O(log₂x)
The function
__builtin_parity(x)
This function is used to check whether the number of 1
bits in the binary representation of x is odd or even.
It returns TRUE (1) if the number of 1 bits is odd,
otherwise, it returns FALSE (0).
Time complexity: O(log₂x)
The function__builtin_clz(x)
This function counts the number of consecutive 0 bits before
the first 1 bit in the binary representation of x, from left to
right.
Note:
● This function only works with unsigned integers of type int.
● For long data type, you can use the __builtin_clzl() function,
and for long long, you can use the __builtin_clzll() function in
a similar manner.
● If the input value of these functions is 0, the return value is
undefined.
Time complexity: O(log₂x)
The function__builtin_clz(x)
The function __builtin_ctz(x)

Opposite to the __builtin_clz() function, this function is used to count


the number of consecutive 0 bits after the last 1 bit in the binary
representation of x, from right to left. Similarly, we have the
__builtin_ctzl() function for the long data type and the __builtin_ctzll()
function for the long long data type.
Important notes:
● Like __builtin_clz(), if the input value is 0, the return value is
undefined.
● This function does not work with signed integers.

Time complexity: O(log₂x)


The function __builtin_ctz(x)
ation
SOME
EXAMPLES
Problem: Given a positive
integer n, find a set consisting
of k elements a[1],a[2], … ,
a[k] that satisfies:

Problem:
Analysis: Transformati
● Observation: This is
equivalent to representing n in on
binary form.
● In fact, the problem can be
solved using a simple method
with a time complexity of O(log
n), but that is not the most
Optimized solution:
+ Essentially, the O(log⁡n)
approach is just about finding the
positions where the bits are equal
to 1.
l v e t h e + Observation: Since n≤10^9, the
o ss i b l e t o s o
Is i t p maximum bit length is only 32
ro b l e m i n
above p ) t i m e bits.
x i m a t e l y O ( 3 2 -> We can iterate through each bit
appr o ) ?
y ( w i t h n ≤ 1 e 9
co m p l e x i t to check because the time
complexity is very low.
+ So, is there a way to determine
whether the ii-th bit is 1 in O(1)
time?
-> Based on bitwise properties, it
is easy to check if the ii-th bit is 1
using the condition: if ((n >> i) &
n >> i is to shift i
bits to the right
For example: n=10
(binary
representation is
00001101)
-> n >> 1 =
explain
00000110
n >> 2 =
00000011
n >> 3 =
Bitwise operations 2
Summarize the
problem
Given two numbers a and b, we obtain a number c through
the following operations:
● Bits 0 to 4 of c are the result of the XOR operation on the
corresponding bits of a and b. For example, bit 0 of c is the
value of bit 0 of a XOR bit 0 of b.
● Bits 5 to 9 are the result of the AND operation on the
corresponding bits of a and b.
● Bits 10 to 14 are the result of the OR operation on the
corresponding bits of a and b.
Constraints:
● 1 <= q <= 10^5
● 0 <= a < b <= 2^15
We can solve this problem using a basic
iteration approach. Let the final result of
the query be the variable answer.
Idea Iterate from 0 to the highest bit position
of a and b minus 1. For each position,
extract the corresponding bits of a and
b, called bit_a and bit_b. Then, based
on the current position, use an if
condition to determine the value of a
variable res, which is calculated using
bit_a XOR bit_b, bit_a AND bit_b, or
bit_a OR bit_b.
Once res is obtained, assign its value to
the corresponding position in the
answer variable.
One important thing to note is that the
Operations

Calculate the bit length of a number


Calculating the length of a variable is
equivalent to finding the position of its
most significant bit (MSB), which means
the first bit with a value of 1 when viewed
from left to right, or the last bit with a
value of 1 when viewed from right to left.
To find the position of the MSB of a
number, we initialize a variable cur equal
to the value of the given number. Then, The above code is the implementation of the bit
we continuously right-shift this variable length calculation operation, where bit is the
while increasing a counter until the number whose bit length needs to be calculated,
variable becomes zero. The result is the and var is a temporary variable used in the right-
number of right-shift operations required shift operation.
to reduce the variable to zero.
Operations

Find the i-th bit of a number


To explain more easily, let's consider the variable pos as the
position of the bit we want to find in the number a. We observe that
the pos-th bit of a can only have two values: 0 or 1. Therefore, the
simplest way is to check whether the pos-th bit of a is 0 or 1 and
return the corresponding value.
To determine whether the pos-th bit of a is 0 or 1, we take the
number 1 and left-shift it by pos positions. If a & (1 << pos) is 0,
the pos-th bit is 0; otherwise, it is 1.
To explain this method, we need to understand that AND-ing any
number with 0 will always return 0. When we left-shift 1 by pos
positions, only the bit at position pos is 1, and all other bits are 0.
Thus, when performing the AND operation with a, all bits except
the pos-th bit will return 0. As a result, the value of the expression a
& (1 << pos) entirely depends on the value of the pos-th bit of a.
If the pos-th bit of a is 1, the operation a & (1 << pos) will return a
non-zero value. If the pos-th bit of a is 0, the operation will return 0.
Operations

Assign the value val to the pos-th bit of the


number a
If we consider a more general case, it would be
necessary to check whether the pos-th bit of a already
has the value 1. However, in this problem, the final
result variable (answer) is initially 0, and because we
iterate in order, the bit we need to assign a value to
always has an initial value of 0. Moreover, the val
variable only has two possible values, 0 and 1.
Therefore, we only need to left-shift the bit val by pos
times and return the result as the value of a OR (val <<
pos). In other words, we move the bit val to the correct
pos position and set the pos-th bit of a to val using the
Nguyen Quoc Tien

CAPTIAN
PROBLEM

GROUP 1
problem

Captain Prime is on an expedition to a mysterious land in the vast


ocean with his most elite legion. Along the way, many dark forces
attack the soldiers' spirits, causing chaos and making them lose
control. As a result, he decided to throw some soldiers into the sea.
Whether a soldier is thrown into the sea depends on the identification
number (id) they carry.

Nguyen Quoc Tien


problem

The ship is divided into three sections:


LEFT, RIGHT, and CENTRAL. Each soldier on the ship is assigned to
work in one section based on their id number. The working areas are
defined as follows: Soldiers assigned to work must have an id number
that is a prime number and does not contain the digit 0.

Nguyen Quoc Tien


problem

In addition, each section has specific requirements: CENTRAL


section: A soldier will work in the middle of the ship if:
When the digits on the left of the id are progressively removed in
order, the remaining numbers are all prime numbers.
Similarly, when the digits on the right of the id are progressively
removed, the remaining numbers are all prime numbers.

Nguyen Quoc Tien


problem

LEFT section: A soldier will work on the left side of the ship if:
When the digits on the left of the id are progressively removed in
order, the remaining numbers are all prime numbers.
RIGHT section: A soldier will work on the right side of the ship if:
When the digits on the right of the id are progressively removed in
order, the remaining numbers are all prime numbers.
DEAD:
A soldier will be thrown into the sea if they do not qualify to work in
any section of the ship.

Nguyen Quoc Tien


Problem Summary
Given Q queries, each containing an integer n, check the following:
● If n remains a prime number when you successively remove digits
from both the left and right, print "CENTRAL".
● If n remains a prime number when you successively remove digits
only from the right, print "RIGHT".
● If n remains a prime number when you successively remove digits
only from the left, print "LEFT".
● If none of the above conditions are satisfied, print "DEAD".

Nguyen Quoc Tien


Problem Summary
Constraints: Subtasks:
● Q ≤ 10^5 ● Subtask 1: Q ≤ 10^5, n
● n ≤ 10^8 ≤ 100
● Subtask 2: Q ≤ 10^5, n
≤ 10^6
● Subtask 3: Q ≤ 10^5, n
≤ 10^8

Nguyen Quoc Tien


Method 1: Brute Force
For each n, we iterate with a time complexity of
O((log⁡10n+1)×q×sqrt{n}), which is only suitable for subtask 1.
We improve this using the Sieve of Eratosthenes, achieving a
total complexity of O(n×log⁡log⁡n+q), which is sufficient for subtask
2.

Nguyen Quoc Tien


Method 2:
The problem with using the standard Sieve of
Eratosthenes is that each number requires 1 byte (8 bits).
When n = 10^8, it needs approximately 100 MB of memory,
which is very wasteful.
Can we use 1 bit for marking instead of 8 bits?
Storing each number using 1 bit instead of 1 byte saves 8
times the memory compared to using a bool array.
It is also faster due to bitwise operations.
With the prime[0] element in the prime array, we can store
the status of 32 consecutive numbers. Nguyen Quoc Tien
ILLUSTRATIONS

This only significantly improves storage memory, but the time efficiency is still not optimal, so further
improvements are needed.
Since all prime numbers except 2 are odd, we can skip all even numbers and only store the state of
odd numbers. Thus, prime[0] will store the states of 1, 3, 5, 7, … instead of all numbers from 1 to N.
This approach saves more memory and significantly increases processing speed.
Example:

Nguyen Quoc Tien


Nguyen Quoc Tien
Nguyen Quoc Tien
Nguyen Quoc Tien
Nguyen Quoc Tien
PROS
&
CONS
PROS
Optimize memory, simplify the program.
Fast processing speed (executed directly on the CPU
hardware, increasing efficiency in applications like
encryption, game graphics, AI, etc.).
Memory-efficient.
Algorithm optimization:
●Multiplication by 2 → x << 1 (shift left by 1 bit).
●Division by 2 → x >> 1 (shift right by 1 bit).
●Checking odd/even numbers → x & 1 (if the result is
1, it's odd; if 0, it's even).
Useful in embedded programming
(microcontrollers) (direct bitwise operations for
hardware control).
CONS
• Hard to understand and read source code.
• Error-prone due to mistakes in bit manipulation (overflow,
sign errors, logic errors).
• Poor scalability (tied to specific sizes like 8, 16, 32, 64
bits, causing issues during conversion).
• Unsuitable for complex calculations (good for flag
handling, data compression, and algorithm optimization,
but cannot fully replace arithmetic operations).
• Difficult to optimize on modern processors (modern
CPUs have specialized instructions for arithmetic and vector
operations, making manual bit manipulation less
advantageous).
THANK
YOU

You might also like