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.
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)
Using Bit Manipulation:
Approach
Bitwise Operation Approach:
- Step 1: Create a mask with only the k-th bit set to
0
and all other bits set to1
by inverting a mask where only the k-th bit is1
. - Step 2: Use the AND (
&
) operation with this mask to clear the k-th bit of the number.
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.