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