-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopy Set Bits in Range.java
More file actions
79 lines (63 loc) · 1.56 KB
/
Copy Set Bits in Range.java
File metadata and controls
79 lines (63 loc) · 1.56 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
71
72
73
74
75
76
77
78
79
//{ Driver Code Starts
//Initial Template for Java
import java.io.*;
import java.util.*;
class GFG{
public static void main(String args[])throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(in.readLine());
while(t-- > 0){
String line[] = in.readLine().trim().split("\\s+");
int x = Integer.parseInt(line[0]);
int y = Integer.parseInt(line[1]);
int l = Integer.parseInt(line[2]);
int r = Integer.parseInt(line[3]);
Solution ob = new Solution();
System.out.println(ob.setSetBit(x, y, l, r));
}
}
}
// } Driver Code Ends
//LOGIC
/*
8 - > 1000
5 - > 101
x = 8
y = 5
left = 1
right = 4
Expected Output = 1101
From 1 to 4 in y (from left to right)
101
To get this digits within the range left to right
First create mask = 1
In binary 0001
Here right = 4 and left = 1
So right - left + 1 = 4
Shift mask 4 times left
mask = mask << 4
now mask = 1000
mask - 1
now mask = 0111
Shift mask left by left - 1
Here left = 0 So 0 times
So mask = 0111
Now Do AND mask and y
0111 & 0101 = 0101
now mask = 0101
Do OR on mask and x
1000 | 0101 = 1101
Result = 1101
*/
//User function Template for Java
class Solution{
static int setSetBit(int x, int y, int l, int r){
// code here
int mask = (1 << (r-l+1));
mask--;
mask = (mask << l-1);
int y1 = y & mask;
x = x | y1;
return x;
}
}