Problem Statement
Given an integer number
and an integer k
, toggle (flip) the k-th bit of the binary representation of the number
. The bit positions are indexed from 0
(rightmost bit). If the k-th bit is 0
, it should be set to 1
; if it is 1
, it should be set to 0
.
Input:
number
: An integer whose k-th bit needs to be toggled.k
: The index of the bit to be toggled.
Output:
- The integer with the k-th bit toggled.
Constraints:
0 ≤ number ≤ 2^31 - 1
(32-bit unsigned integer)0 ≤ k < 32
Examples
Example 1:
Input: number = 10 (Binary: 1010), k = 2
Output: 14 (Binary: 1110)
Explanation:
The original number is 10 (binary 1010).
We need to toggle the 2nd bit.
The mask to toggle the 2nd bit is 0100.
Applying the XOR operation results in 1110 (binary), which is 14 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 toggle the 3rd bit.
The mask to toggle the 3rd bit is 1000.
Applying the XOR operation results in 10101 (binary), which is 21 in decimal.
Approaches
1️⃣ Bitwise Operation Approach:
Approach
- Step 1: Create a mask with only the k-th bit set to
1
by left-shifting1
byk
positions:1 << k
. - Step 2: Use the XOR (
^
) operator with this mask to toggle the k-th bit. XOR will flip the bit at positionk
.
Dry Run:
Let’s dry run an example with number = 10
and k = 2
.
- Initial Values:
number
=10
(Binary:1010
)k
=2
- Create Mask:
mask = 1 << k
1 << k = 1 << 2 = 4
(Binary:0100
)
- Perform Bitwise XOR Operation:
result = number ^ mask
result = 1010 ^ 0100 = 1110
(Binary:14
in decimal)
Code:
#include <iostream>
using namespace std;
int toggleKthBit(int number, int k) {
// Create a mask where only the k-th bit is set to 1
int mask = 1 << k;
// Use bitwise XOR to toggle 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 toggle (k): ";
cin >> k;
int result = toggleKthBit(number, k);
cout << "Number after toggling 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.