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

文章介绍了如何在32位整数中进行左旋位操作,包括两种方法:一是通过右移和位或组合实现,二是直接左移。重点在于处理可能溢出的情况并确保正确性。

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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值