-
Notifications
You must be signed in to change notification settings - Fork 290
/
Copy pathClearAllBitsFromMSB.cpp
61 lines (37 loc) · 944 Bytes
/
ClearAllBitsFromMSB.cpp
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
/*
You are given two integers N and i. You need to clear all bits from MSB to ith bit (start i from right to left) and return the updated N.
Counting of bits starts from 0 from right to left.
Input Format :
Two integers N and i (separated by space)
Output Format :
Updated N
Sample Input 1 :
15 2
Sample Output 1 :
3
Sample Output 1 Explanation :
We need to clear all bits from MSB to ith bit i.e. clear all bits except 0th and 1st.
Sample Input 2 :
4 4
Sample Output 2 :
4
*/
int clearAllBits(int n, int i){
/* Don't write main().
* Don't read input, it is passed as function argument.
* Return output and don't print it.
* Taking input and printing output is handled automatically.
*/
int a=1<<i;
int b=a-1;
int ans=n & b;
return ans;
}
#include <iostream>
using namespace std;
int main() {
int n, i;
cin >> n >> i;
cout<< clearAllBits(n, i) <<endl;
return 0;
}