-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
67 lines (58 loc) · 2.34 KB
/
Copy pathSolution.java
File metadata and controls
67 lines (58 loc) · 2.34 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
import java.util.*;
public class BitStringFlicking {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String[] parts = scanner.nextLine().split(" ");
String command = parts[0];
if (command.equals("N")) {
int num = Integer.parseInt(parts[1]);
System.out.println(notOperation(num));
} else if (command.equals("A") || command.equals("O") || command.equals("X")) {
int num1 = Integer.parseInt(parts[1]);
int num2 = Integer.parseInt(parts[2]);
System.out.println(bitwiseOperation(command, num1, num2));
} else {
int shiftAmount = Integer.parseInt(parts[1]);
int num = Integer.parseInt(parts[2]);
System.out.println(shiftOperation(command, shiftAmount, num));
}
}
scanner.close();
}
private static int notOperation(int num) {
int bitLength = Integer.toBinaryString(num).length();
int mask = (1 << bitLength) - 1;
return (~num) & mask;
}
private static int bitwiseOperation(String command, int num1, int num2) {
return switch (command) {
case "A" -> num1 & num2;
case "O" -> num1 | num2;
case "X" -> num1 ^ num2;
default -> 0;
};
}
private static int shiftOperation(String command, int shift, int num) {
String binary = Integer.toBinaryString(num);
return switch (command) {
case "RS" -> num >> shift;
case "LS" -> num << shift;
case "RC" -> rotateRight(binary, shift);
case "LC" -> rotateLeft(binary, shift);
default -> 0;
};
}
private static int rotateRight(String binary, int shift) {
int len = binary.length();
shift %= len;
String rotated = binary.substring(len - shift) + binary.substring(0, len - shift);
return Integer.parseInt(rotated, 2);
}
private static int rotateLeft(String binary, int shift) {
int len = binary.length();
shift %= len;
String rotated = binary.substring(shift) + binary.substring(0, shift);
return Integer.parseInt(rotated, 2);
}
}