-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdate_ith_bit.cpp
More file actions
70 lines (66 loc) · 4.12 KB
/
update_ith_bit.cpp
File metadata and controls
70 lines (66 loc) · 4.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <bits/stdc++.h>
using namespace std;
int updateIthBit(int num, int i, int val) {
int mask = ~(1 << i);
num = num & mask;
num = num | (val << i);
return num;
}
int main() {
int n, i, v;
cin >> n >> i >> v;
cout << updateIthBit(n, i, v) << '\n';
return 0;
}
/*
─────────────────────────────────────────────────────────────────
Example Run
─────────────────────────────────────────────────────────────────
Input:
n = 13, i = 2, val = 0
─────────────────────────────────────────────────────────────────
Binary Representation
─────────────────────────────────────────────────────────────────
13 = (1101)₂
↑
bit position = 2 ← (counting from 0, rightmost bit)
─────────────────────────────────────────────────────────────────
Create a Mask to Clear Bit i
─────────────────────────────────────────────────────────────────
(1 << i) = (1 << 2)
= (00000100)₂
~(1 << i) = ~(00000100)₂
= (11111011)₂ ← bit 2 is 0, others 1
─────────────────────────────────────────────────────────────────
Clear Bit i
─────────────────────────────────────────────────────────────────
num = 00001101 (13)
mask = 11111011
num & mask = 00001101
&11111011
─────────
00001001 (9)
After this step, bit 2 is cleared (set to 0).
─────────────────────────────────────────────────────────────────
Set Bit i to Desired Value (val)
─────────────────────────────────────────────────────────────────
val = 0
(val << i) = (0 << 2)
= 00000000
num | (val << i) = 00001001 | 00000000
= 00001001
─────────────────────────────────────────────────────────────────
Final Result
─────────────────────────────────────────────────────────────────
Binary → (1001)₂
Decimal → 9
Output:
9
─────────────────────────────────────────────────────────────────
Intuition:
─────────────────────────────────────────────────────────────────
updateIthBit(n, i, val)
• Clears the i-th bit of n
• Then sets it to val (0 or 1)
─────────────────────────────────────────────────────────────────
*/