Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package BitRotation;
- import java.util.Scanner;
- public class BitRotation_Broken {
- final static String SET = "set";
- final static String UNSET = "unset";
- final static String RIGHT = "right";
- final static String LEFT = "left";
- public static byte setOrUnsetBitAtPosition(byte number, int position, String option){
- if (option.equals(SET)) {
- number = (byte) (number | (1 << position));
- } else if (option.equals(UNSET)) {
- number = (byte) (number & ~(1 << position));
- }
- return number;
- }
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- byte number = Byte.parseByte(input.nextLine());
- byte rotations = Byte.parseByte(input.nextLine());
- for (int i = 0; i < rotations; i++) {
- String direction = input.nextLine();
- // == does not work for compare strings
- String bitRepresentationOfTheNumber = Integer.toBinaryString(number);
- if (direction.equals(RIGHT)) {
- // get 0 bit
- int bitAt0Position = (number >> 0) & 1;
- number = (byte) (number >> 1);
- // set 0 on 5
- if (bitAt0Position == 1) {
- number = setOrUnsetBitAtPosition(number, 5, SET);
- }
- else if (bitAt0Position == 0) {
- number = setOrUnsetBitAtPosition(number, 5, UNSET);
- }
- } else if (direction.equals(LEFT)) {
- // get 5th bit
- int bitAt6Position = (number >> 5) & 1;
- number = (byte) (number << 1);
- // set 5th bit on 0 position
- if (bitAt6Position == 1) {
- number = setOrUnsetBitAtPosition(number, 0, SET);
- }
- else if (bitAt6Position == 0) {
- number = setOrUnsetBitAtPosition(number, 0, UNSET);
- }
- number = setOrUnsetBitAtPosition(number, 6, UNSET);
- }
- }
- System.out.println(number);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement