Problems - Set 1
Easy
1. Addition of Two Numbers
The provided code snippet implements binary addition without using the built-in +
operator.
Identifying Bits Set to 1:
Bitwise AND compares the corresponding bits of
a
andb
.It returns 1 only if the bits in both positions of
a
andb
are 1. Otherwise, it returns 0.
Significance in Carry Calculation:
In binary addition, a carry is generated when adding two bits that are both 1 (e.g., 1 + 1 = 10, where 1 is the carry bit).
The
carry = a & b;
line essentially identifies the positions where botha
andb
have bits set to 1. These positions will generate a carry bit during the addition.
Example:
Let's consider a = 5 (binary: 101)
and b = 3 (binary: 011)
.
a & b = 001
. Here, only the least significant bit (LSB) position has 1s in botha
andb
, indicating a carry will be generated for this bit position.
Using Carry for Addition:
The subsequent line
a = a ^ b;
performs bitwise XOR (^) ona
andb
. XOR is 1 only when the corresponding bits are different.This line effectively adds
a
andb
without considering the carry for the current bit position. The carry will be addressed in the next iteration of the loop.
Carry bit is shifted left
These carry bits are then shifted left in the next line (b = carry << 1;
) to be added in the subsequent bit positions (next bit position) of a
and b
.
2. Swapping the 2 numbers
3. Convert Decimal to Binary Conversion
By iterating through each bit position and checking its value using the right shift and bitwise AND operations, the code determines whether each bit in the binary representation of n
is 0 or 1.
4. Check if a Number is Power of Two
Given a number n
, check if it is a power of two.
Approach
A number is a power of two if it has only one bit set to 1 in its binary representation. For example:
1 →
0001
( 2^0 )2 →
0010
( 2^1 )4 →
0100
( 2^2 )8 →
1000
( 2^3 )
5. Count the Number of Set Bits (Hamming Weight)
Given an integer, count the number of 1
s in its binary representation.
Approach: Use n & (n - 1)
to remove the lowest set bit in a loop.
6. Find the Single Non-Repeating Element (XOR Trick)
Given an array where every element appears twice except for one, find the single element.
Approach:
XORing a number with itself results in
0
(a ^ a = 0
).XORing all numbers cancels out the duplicates, leaving only the unique number.
Medium
1. Reverse Bits of an Integer
Given a 32-bit integer, reverse its bits.
Approach:
Iterate through the bits, shifting the result left and adding the last bit of
n
to it.
Java Solution:
2. Find the Missing Number
Problem Statement:
Given an array of size n
containing numbers from 0
to n
with one missing, find the missing number.
Approach: Use XOR: missing = (0 ^ 1 ^ 2 ^ ... ^ n) ^ (arr[0] ^ arr[1] ^ ... ^ arr[n-1])
Difficult
Last updated
Was this helpful?