-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclear_last_i_bits.cpp
More file actions
59 lines (55 loc) · 2.92 KB
/
clear_last_i_bits.cpp
File metadata and controls
59 lines (55 loc) · 2.92 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
#include <bits/stdc++.h>
using namespace std;
int clearLastIBits(int n, int i) {
int mask = ~((1 << i) - 1);
return (n & mask);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, i;
cin >> n >> i;
cout << clearLastIBits(n, i) << '\n';
return 0;
}
/*
──────────────────────────────────────────────────────────
Example Run
──────────────────────────────────────────────────────────
Input
──────────────────────────────────────────────────────────
n = 59 i = 3
Binary of 59 = (111011)
↑↑↑
clear these last 3 bits (i = 3)
──────────────────────────────────────────────────────────
Solving Procedure
──────────────────────────────────────────────────────────
Step 1: (1 << i)
= (1 << 3)
= (00001000)
Step 2: (1 << i) - 1
= (00001000) - 1
= (00000111)
Step 3: mask = ~((1 << i) - 1)
= ~(00000111)
= 11111000
Step 4: n & mask = (111011) & (111000)
= (111000)
──────────────────────────────────────────────────────────
Result:
──────────────────────────────────────────────────────────
Binary → 111000
Decimal → 56
Output:
56
──────────────────────────────────────────────────────────
Concept
──────────────────────────────────────────────────────────
"Clearing last i bits" means
turning the i least significant bits to 0,
while keeping higher bits unchanged.
──────────────────────────────────────────────────────────
Note: ((~0) << i) will also work as mask in C and C++
──────────────────────────────────────────────────────────
*/