0% found this document useful (0 votes)
23 views

Bit Manipulation

Uploaded by

shuklarivya27
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)
23 views

Bit Manipulation

Uploaded by

shuklarivya27
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/ 39

Advance Algorithmic

& Problem Solving

Dr. Subhash Chandra Gupt


Assistant Professor, SCSE
Galgotias University
Introduction to Algorithmic Thinking
1 Importance of Problem-Solving Skills

Learn why problem-solving skills are crucial in coding interviews and how
they contribute to better algorithmic thinking.

2 Und ersta nd i ng Ti me a nd S p a ce Comp l ex ity

Gain a solid understanding of time and space complexity and how it


affects the efficiency of algorithms.

3 U n d e r s t a n d i n g Va r i o u s E r r o r s

Identification of programming errors, its significance, and the handling


mechanism is important.
Importance of Problem-Solving Skills

Example: To go from city “A” to city “B”.


Options: by flight, by bus, by train and also by bicycle.

Depending on the availability and convenience, we choose the one


that suits us.

Similarly, in computer science, a sorting problem has many


algorithms, like insertion sort, selection sort, quick sort and many
more.

Algorithm analysis helps us to determine which algorithm is most


efficient in terms of time and space consumed.
Importance of Problem-Solving Skills

Geeksforgeeks:
https://www.geeksforgeeks.org/

Codecademy: https://www.codecademy.com/

LeetCode: https://leetcode.com/

Hackerrank: https://www.hackerrank.com/

CodeChef: https://www.codechef.com/

Topcoder: https://www.topcoder.com/

GitHub: https://github.com/
Placement
• Academic curriculum
• Industry Demand
• Fill the Gap between Academic and
Industry

• How many of you want PLACEMENT?


• What’s your strategies?
• How to compete with other students globally?
Course Pack
Syllabus
Let’s discuss some problem :

• Could you add two number without using + or - operator

• Could you divide a number by 2 without using / operator

• Could you multiply a number by 2 without using * operator

• Could you check a number is even or odd without using %


operator
Bit Manipulation Fundamentals
Bitwise manipulation involves performing operations on individual bits
of binary numbers.

In computing, data is often represented in binary format, where each


digit is a bit (0 or 1). Bitwise operations are low-level operations that
directly manipulate bits.

1 Exploring Bitwise Operations

Dive into the world of bitwise operations and unravel their potential
applications in problem-solving.

2 Common Use Cases for Bitwise Operations

Discover the common use cases where bitwise operations prove to be


powerful tools in algorithmic thinking.
1 Exploring Bitwise Operations

1. AND (&):
• Takes two binary numbers and performs a bitwise AND operation
on each pair of corresponding bits.
2. OR (|):
• Performs a bitwise OR operation on each pair of corresponding
bits in two binary numbers.
3. XOR (^):
• Performs a bitwise XOR (exclusive OR) operation on each pair of
corresponding bits.
4. NOT (~):
• Inverts each bit of a binary number, changing 0s to 1s and 1s to 0s.
5. Left Shift (<<) and Right Shift (>>):
• Shifts the bits of a binary number to the left or right by a specified
number of positions.

These bitwise operations are often used in programming for tasks such as
setting or clearing specific bits, checking the parity of numbers, or
optimizing certain algorithms.
Bitwise Real Case Applications:
Bitwise Flags:
It is commonly used to represent sets of Boolean flags. Each flag corresponds to a specific bit,
and bitwise operations can be used to set, clear, or toggle individual flags.

# Define flags
READ = 1 # 0001
WRITE = 2 # 0010
EXECUTE = 4 # 0100

# Set flags
permissions = 0 # 0000
permissions |= READ | WRITE
print(bin(permissions))

Optimizations:
Bitwise operations are sometimes used for low-level optimizations, particularly in embedded
systems or performance-critical applications. For example, bitwise AND with a power of two is
equivalent to taking the modulus by that power, which can be more efficient in certain scenarios.

# Check if a number is even using bitwise AND


def is_even(num):
return num & 1 == 0

print(is_even(10)) # Output: True


print(is_even(7)) # Output: False
Bitwise Real Case Applications:
Cryptography:
Bitwise operations play a crucial role in cryptographic algorithms. XOR operations, for
instance, are used in encryption and decryption processes.

# XOR encryption and decryption


def xor_encrypt_decrypt(data, key):
encrypted_data = data ^ key
decrypted_data = encrypted_data ^ key
return encrypted_data, decrypted_data
data_to_encrypt = 0b10101010
encryption_key = 0b11001100
encrypted, decrypted = xor_encrypt_decrypt(data_to_encrypt, encryption_key)
print(bin(encrypted)) # Output: 0b01100110
print(bin(decrypted)) # Output: 0b10101010

Graphics Programming:
In graphics programming, bitwise operations can be employed for tasks such as pixel
manipulation, color blending, and image processing.

# Color blending using bitwise OR


def blend_colors(color1, color2):
return color1 | color2
color1 = 0b11001100
color2 = 0b00110011
blended_color = blend_colors(color1, color2)
print(bin(blended_color)) # Output: 0b11111111
Bitwise Real Case Applications:
Network Programming:
Bitwise operations are used in networking to manipulate and analyze network
protocols at the binary level. For example, in subnetting and IP address
manipulation, Check if a specific flag is set in a network packet.

File Compression:
Bitwise operations are utilized in file compression algorithms, where individual bits
are manipulated to represent patterns and compress data.

Embedded Systems:
In embedded systems programming, where resources are often limited, bitwise
operations can be used to efficiently control hardware registers and manage
memory.
Examples of Bit Manipulation in
Coding Challenges

1 Application of Bitwise Operations

See how bitwise operations can be applied to solve common coding


problems such as GCD calculations and power sets.

2 Exploring Problem Scenarios

Dive into real-world problem scenarios where bit manipulation techniques


can be effectively employed.
Bitwise Programming Tips and Tricks:

1.Swapping Two Variables:

void swap(int *a, int *b)


{

}
Bitwise Programming Tips and Tricks:

1.Swapping Two Variables:

void swap(int *a, int *b) {


*a ^= *b;
*b ^= *a;
*a ^= *b;
}
Bitwise Programming Tips and Tricks:

2. Check if a Number is Power of 2:

int is_power_of_two(unsigned int x)


{

}
Bitwise Programming Tips and Tricks:

2. Check if a Number is Power of 2:

int is_power_of_two(unsigned int x)


{
return (x != 0) && ((x & (x - 1)) == 0);
}
Bitwise Programming Tips and Tricks:

3. Count Set Bits (Hamming Weight):

int count_set_bits(unsigned int n)


{

}
Bitwise Programming Tips and Tricks:

3. Count Set Bits (Hamming Weight):

int count_set_bits(unsigned int n)


{
int count = 0; int count_set_bits(int
while (n) n)
{ {
count += n & 1; int count = 0;
n >>= 1; while (n>0)
} {
return count; n = n & (n-1);
} count +=1;
}
return count;
Bitwise Programming Tips and Tricks:

4. Toggle nth Bit:

unsigned int toggle_nth_bit(unsigned int x, int n)


{

}
Bitwise Programming Tips and Tricks:

4. Toggle nth Bit:

unsigned int toggle_nth_bit(unsigned int x, int n)


{
return x ^ (1 << n);
}
Bitwise Programming Tips and Tricks:
5. Set Nth Bit:

unsigned int set_nth_bit(unsigned int x, int n)


{

}
Bitwise Programming Tips and Tricks:

5. Set Nth Bit:

unsigned int set_nth_bit(unsigned int x, int n)


{
return x | (1 << n);
}
Bitwise Programming Tips and Tricks:

6. Clear Nth Bit:

unsigned int clear_nth_bit(unsigned int x, int n)


{

}
Bitwise Programming Tips and Tricks:

6. Clear Nth Bit:

unsigned int clear_nth_bit(unsigned int x, int n)


{
return x & ~(1 << n);
}
Bitwise Programming Tips and Tricks:

7. Check if Nth Bit is Set:

int is_nth_bit_set(unsigned int x, int n)


{

}
Bitwise Programming Tips and Tricks:

7. Check if Nth Bit is Set:

int is_nth_bit_set(unsigned int x, int n)


{
return (x >> n) & 1;
}
Hands-on Practice
Question: Write a function to add two numbers without using arithmetic
+ or – operator.

Approach?

Running Time and Space requirement?

int add(int a, int b)


{

}
Hands-on Practice
Question: Write a function to add two numbers without using arithmetic
+ or – operator.

Approach?

Running Time and Space requirement?

int add(int a, int b) {


while (b != 0) {
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
Hands-on Practice
Question: Let a non-empty array of integers ARR is given where every element
appears twice except for one.
Find that single one.

ARR: 5, 4, 2, 5, 4
Output: 2

Approach?

Running Time and Space requirement?

function singleNumber(nums)
{

}
Hands-on Practice
Question: Let a non-empty array of integers ARR is given where every element
appears twice except for one.
Find that single one.

ARR: 5, 4, 2, 5, 4
Output: 2

Approach?

Running Time and Space requirement?

function singleNumber(nums) {
let answer = 0;
for (let i = 0; i < nums.length; i++) {
answer ^= nums[i];
}

return answer;
}
Hands-on Practice
Given a number N, the task is to find the XOR of all numbers from 1
to N.
Examples :
Input : N = 6
Output : 7
// 1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6 = 7

Input : N = 7
Output : 0
// 1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6 ^ 7 = 0
Solution:
Find the remainder of N by moduling it with 4.
If rem = 0, then xor will be same as N.
If rem = 1, then xor will be 1.
If rem = 2, then xor will be N+1.
If rem = 3 ,then xor will be 0
U n d e r s t a n d i n g Va r i o u s E rro r s

Recognizing and addressing these errors efficiently is crucial for


success.

1. Syntax Errors - Syntax errors can prevent the code from compiling

2. Logical Errors - Logical errors result in incorrect program output

3. Runtime Errors - Such as segmentation faults or null pointer dereferences

4. Time Limit Exceeded (TLE) - Exceeding the allowed execution time leads to
rejection of the solution, even if it produces correct results.

5. Memory Limit Exceeded (MLE) - If the program uses more memory than
allowed, it can result in an MLE error.

6. Incorrect Input Handling - Incorrect parsing of input can lead to incorrect


results or runtime errors.
Any question?
Thank you!
Thank you!
Thank you!
Thank you!

You might also like