o_ignatov

BitRoller

Oct 19th, 2017
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4.  
  5. public class BitRoller {
  6. public static void main(String[] args) throws IOException {
  7. BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  8. int num = Integer.parseInt(reader.readLine());
  9. int freezePos = Integer.parseInt(reader.readLine());
  10. int rollCount = Integer.parseInt(reader.readLine());
  11.  
  12. System.out.println(rollRight(num,freezePos,rollCount));
  13. }
  14. private static int getBit(int num, int position){
  15. return (num >> position) & 1;
  16. }
  17. private static int setBit(int num, int position){return num |= (1 << position);}
  18. private static int unsetBit(int num, int position){return num &= ~(1 << position);}
  19. private static int setPositionWith(int num, int position, int value){ return value==0? unsetBit(num,position): setBit(num,position);}
  20. private static int rollRight(int num, int freezePos, int times){
  21. int freezeValue = getBit(num, freezePos);
  22. //System.out.printf("%d -> %d%n",freezePos,freezeValue);
  23. //System.out.printf("%18s -> %d%n", Integer.toBinaryString( (1 << 19) | num ).substring( 1 ),0);
  24.  
  25. for (int i = 0; i < times; i++) {
  26. int beforePos;
  27. int afterPos;
  28. if (freezePos == 0){
  29. beforePos = 1;
  30. afterPos = 18;
  31. }
  32. else if (freezePos == 18){
  33. beforePos = 0;
  34. afterPos = 17;
  35. }
  36. else {
  37. beforePos = freezePos + 1;
  38. afterPos = freezePos - 1;
  39. }
  40. int beforeValue = getBit(num,beforePos);
  41.  
  42. if (getBit(num,0) == 1 ){
  43. num >>= 1;
  44. num = setBit(num,18);
  45. }
  46. else {
  47. num >>= 1;
  48. }
  49. num = setPositionWith(num,freezePos,freezeValue);
  50. num = setPositionWith(num,afterPos,beforeValue);
  51. //System.out.printf("%18s -> %d%n", Integer.toBinaryString( (1 << 19) | num ).substring( 1 ),i+1);
  52. }
  53. return num;
  54. }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment