main.cpp 1.2 KB

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