Advertisement
Guest User

Untitled

a guest
Feb 4th, 2015
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.45 KB | None | 0 0
  1. package BitRotation;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class BitRotation_Broken {
  6.  
  7. final static String SET = "set";
  8. final static String UNSET = "unset";
  9. final static String RIGHT = "right";
  10. final static String LEFT = "left";
  11.  
  12. public static byte setOrUnsetBitAtPosition(byte number, int position, String option){
  13.  
  14. if (option.equals(SET)) {
  15. number = (byte) (number | (1 << position));
  16. } else if (option.equals(UNSET)) {
  17. number = (byte) (number & ~(1 << position));
  18. }
  19. return number;
  20. }
  21.  
  22. public static void main(String[] args) {
  23. Scanner input = new Scanner(System.in);
  24.  
  25. byte number = Byte.parseByte(input.nextLine());
  26. byte rotations = Byte.parseByte(input.nextLine());
  27.  
  28. for (int i = 0; i < rotations; i++) {
  29. String direction = input.nextLine();
  30.  
  31.  
  32. // == does not work for compare strings
  33.  
  34. String bitRepresentationOfTheNumber = Integer.toBinaryString(number);
  35.  
  36. if (direction.equals(RIGHT)) {
  37. // get 0 bit
  38. int bitAt0Position = (number >> 0) & 1;
  39.  
  40. number = (byte) (number >> 1);
  41. // set 0 on 5
  42.  
  43. if (bitAt0Position == 1) {
  44. number = setOrUnsetBitAtPosition(number, 5, SET);
  45. }
  46. else if (bitAt0Position == 0) {
  47. number = setOrUnsetBitAtPosition(number, 5, UNSET);
  48. }
  49. } else if (direction.equals(LEFT)) {
  50. // get 5th bit
  51. int bitAt6Position = (number >> 5) & 1;
  52.  
  53. number = (byte) (number << 1);
  54. // set 5th bit on 0 position
  55.  
  56. if (bitAt6Position == 1) {
  57. number = setOrUnsetBitAtPosition(number, 0, SET);
  58. }
  59. else if (bitAt6Position == 0) {
  60. number = setOrUnsetBitAtPosition(number, 0, UNSET);
  61. }
  62.  
  63. number = setOrUnsetBitAtPosition(number, 6, UNSET);
  64. }
  65. }
  66.  
  67. System.out.println(number);
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement