Problem Statement
Given an integer number
and an integer k
, clear (set to 0
) the k-th bit of the binary representation of the number
. The bit positions are indexed from 0
(rightmost bit).
Input:
number
: An integer whose k-th bit needs to be cleared.k
: The index of the bit to be cleared.
Output:
- The integer with the k-th bit cleared.
Constraints:
0 ≤ number ≤ 2^31 - 1
(32-bit unsigned integer)0 ≤ k < 32
Examples
Example 1:
Input: number = 15 (Binary: 1111), k = 2
Output: 11 (Binary: 1011)
Explanation:
The original number is 15 (binary 1111).
We need to clear the 2nd bit.
The mask to clear the 2nd bit is 1011.
Applying the AND operation results in 1011 (binary), which is 11 in decimal.
Example 2:
Input: number = 29 (Binary: 11101), k = 3
Output: 21 (Binary: 10101)
Explanation:
The original number is 29 (binary 11101).
We need to clear the 3rd bit.
The mask to clear the 3rd bit is 10101.
Applying the AND operation results in 10101 (binary), which is 21 in decimal.
Different Approaches
1️⃣ Bit Manipulation (Bitwise OR)
Intuition:
- Every bit has a position and value: either 1 (set) or 0 (unset).
- To turn off a bit, you want to force it to 0, without changing other bits.
- We can do this using bitwise AND (
&
) with a special mask that has:- 0 at the k-th bit
- 1 at all other positions
Approach:
Create a mask with all 1s except for the k-th bit:
int mask = ~(1 << k);
1 << k
creates a number with only the k-th bit as 1.~(1 << k)
flips all bits → now the k-th bit is 0, others are 1.
Apply bitwise AND (
&
):result = num & mask;
- This clears the k-th bit, leaving others unchanged.
Dry Run:
Let's dry run an example with number = 29
and k = 3
.
- Initial Values:
number
=29
(Binary:11101
)k
=3
- Create Mask:
mask = ~(1 << k)
1 << k = 1 << 3 = 8
(Binary:1000
)~(1 << k) = ~1000 = 0111
(Binary for~1000
is0111
)
- Perform Bitwise AND Operation:
result = number & mask
result = 11101 & 0111 = 10101
(Binary:21
in decimal)
Code:
#include <iostream>
using namespace std;
int clearKthBit(int number, int k) {
// Create a mask where only the k-th bit is set to 0
int mask = ~(1 << k);
// Use bitwise AND to clear the k-th bit of the number
number = number & mask;
return number;
}
int main() {
int number, k;
cout << "Enter the number: ";
cin >> number;
cout << "Enter the bit position to clear (k): ";
cin >> k;
int result = clearKthBit(number, k);
cout << "Number after clearing the " << k << "-th bit: " << result << endl;
return 0;
}
Complexity Analysis:
- Time Complexity:
O(1)
Each operation is constant time. - Space Complexity:
O(1)
No extra space used.