-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathset_ith_bit.cpp
More file actions
49 lines (45 loc) · 2.25 KB
/
set_ith_bit.cpp
File metadata and controls
49 lines (45 loc) · 2.25 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
#include <bits/stdc++.h>
using namespace std;
int setIthBit(int num, int i) {
int mask = (1 << i);
return (mask | num);
}
int main() {
int n, i;
cin >> n >> i;
cout << setIthBit(n, i) << '\n';
return 0;
}
/*
───────────────────────────────────────────────────────────────────────────────────
Bit Numbering Convention (Important)
───────────────────────────────────────────────────────────────────────────────────
Bits are counted from **right to left**
The **Least Significant Bit (LSB)** — the rightmost bit — is position **0**
The **Most Significant Bit (MSB)** is the leftmost bit
Example:
Binary: 1 0 0 1
Position: 3 2 1 0
↑ ↑
MSB LSB
i = 0 → refers to the rightmost bit
i = 3 → refers to the leftmost bit (in 4-bit example)
───────────────────────────────────────────────────────────────────────────────────
Example Run
───────────────────────────────────────────────────────────────────────────────────
Input:
9 1
Binary of 9 = 1001
↑
set this bit (i = 1)
mask is shorthand for bitmask and i = position
mask = (1 << 1)
= 2
= (00000010)
num | mask = (00001001) | (00000010)
= (00001011)
After setting → 00001011 = 11
Output:
11
───────────────────────────────────────────────────────────────────────────────────
*/