-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBit Manipulation
More file actions
41 lines (36 loc) · 1.4 KB
/
Bit Manipulation
File metadata and controls
41 lines (36 loc) · 1.4 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
Given a 32 bit unsigned integer num and an integer i. Perform following operations on the number -
1. Get ith bit
2. Set ith bit
3. Clear ith bit
Note : For better understanding, we are starting bits from 1 instead 0. (1-based). You have to print space three space
separated values ( as shown in output without a line break) and do not have to return anything.
Example 1:
Input: 70 3
Output: 1 70 66
Explanation: Bit at the 3rd position from LSB is 1. (1 0 0 0 1 1 0) .The value of the given number after setting
the 3rd bit is 70. The value of the given number after clearing 3rd bit is 66. (1 0 0 0 0 1 0)
Example 2:
Input: 8 1
Output: 0 9 8
Explanation: Bit at the first position from LSB is 0. (1 0 0 0) .The value of the given number after setting
the 1st bit is 9. (1 0 0 1). The value of the given number after clearing 1st bit is 8. (1 0 0 0)
--------------------------------------------------------------------------------------------------------------------------
// tc=O(1) sc=O(1)
class Solution {
public:
void bitManipulation(int num, int i) {
// your code here
// int mask= i<<i;
//get ith bit
int get;
if(num & (1<<i-1))
get=1;
else
get=0;
cout<<get<<" " ;
// set ith bit
cout<<(num | (1<<i-1))<<" ";
//clear the ith bit
cout<<(num & (~(1<<i-1)))<<" ";
}
};