LintCode 723 · Rotate Bits - Left (位操作好题)

723 · Rotate Bits - Left
Algorithms

Description
Bit Rotation -—— A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end.

In left rotation, the bits that fall off at left end are put back at right end.

Let n is stored using 8 bits. Left rotation of n =  11100101 by 3 makes n = 00101111 (Left shifted by 3 and first 3 bits are put back in last ). If n is stored using 16 bits or 32 bits then left rotation of n (000…11100101) becomes 00…0011100101000.

In this problem, you can assume that n was stored in 32 Bits.
To give you the number n to be rotated and the number d of digits to move left, please output the value after left rotation.

Only $39.9 for the “Twitter Comment System Project Practice” within a limited time of 7 days!

WeChat Notes Twitter for more information(WeChat ID jiuzhang998)

Example
Example1

Input: n = 123, d = 4
Output: 1968
Explanation:
0000,0000,0000,0000,0000,0000,0111,1010 --> 0000,0000,0000,0000,0000,0111,1010,0000
Example2

Input: n = 127, d = 8
Output: 32512
Explanation:
0000,0000,0000,0000,0000,0000,1111,1111 -->

解法1:将左移d位转换为右移32-d位。另外注意移位过程种可能或超过INT_MAX/MIN,所以要用long long!

class Solution {
public:
    /**
     * @param n: a number
     * @param d: digit needed to be rorated
     * @return: a number
     */
    int leftRotate(int n, int d) {
        d = d % 32;
        d = 32 - d;
        long long x = n;
        for (int i = 0; i < d; i++) {
            x = ((x & 0x1) << 31) | (x >> 1);
        }
        return x;
    }
};

解法2:直接左移

class Solution {
public:
    /**
     * @param n: a number
     * @param d: digit needed to be rorated
     * @return: a number
     */
    int leftRotate(int n, int d) {
        d = d % 32;
        long long x = n;
        for (int i = 0; i < d; i++) {
            x = ((x & 0x31) >> 31) | (x << 1);
        }
        return x;
    }
};

你可能感兴趣的:(leetcode)