code.cpp 1.1 KB

123456789101112131415161718192021222324252627282930
  1. /* C++ offers some bit operations but not bit rotation. To complete that,
  2. * create a function that takes three parameters:
  3. * n: Integer, which in binary representaion should be rotated.
  4. * m: Number of rotation steps that should be performed.
  5. * d: Boolean value; true = rotation right, false = rotation left.
  6. * Your function should return an integer as a result of its rotated
  7. * binary representation.
  8. * bitRotate(8, 1, true) ➞ 4
  9. * 8 in bin: 1000, rotated 1 step to the right: 0100, in dec: 4
  10. * For parameters use unsigned integers only.
  11. */
  12. int bitRotate(int n, int m, bool d) {
  13. int p = n, c = 1, b = 1;
  14. // find the power of the input
  15. while(p/=2) c++;
  16. // short circuit if power and rotations are the same
  17. if(c==m)return n;
  18. // set the bracket for the input
  19. b<<=c;b--;
  20. // check each rotation to see if over the bracket and rotate
  21. for(int i = 0;i<m;i++){
  22. if(d /*right*/){
  23. if(n&1) n += (b+1); n >>= 1;
  24. } else /*left*/ {
  25. n <<= 1; if(n>b) n -= b;
  26. }
  27. }
  28. return n;
  29. // return d? n<<m : n>>m; <<== should be as simple as this
  30. }