[LintCode] Rotate Bits - Left

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

Example

Given n = 123, d = 4
return 183

 

 1 public class Solution {
 2     /*
 3      * @param : a number
 4      * @param : digit needed to be rorated
 5      * @return: a number
 6      */
 7     public int leftRotate(int n, int d) {
 8         if(d <= 0) {
 9             return n;
10         }
11         if(d > 31) {
12             d = d % 32;
13         } 
14         int[] bits = new int[32];
15         for(int i = 0; i < 32; i++) {
16             bits[i] = ((n >>> (31 - i)) & 1);
17         }
18         leftRotateArray(bits, d);
19         int result = 0;
20         for(int i = 0; i < 32; i++) {
21             result |= (bits[31 - i] << i);
22         }
23         return result;
24     }
25     private static void reverse(int[] bits, int startIdx, int endIdx) {
26         while(startIdx < endIdx) {
27             bits[startIdx] ^= bits[endIdx];
28             bits[endIdx] ^= bits[startIdx];
29             bits[startIdx] ^= bits[endIdx];
30             startIdx++;
31             endIdx--;
32         }
33     }
34     private void leftRotateArray(int[] bits, int d) {
35         reverse(bits, 0, d - 1);
36         reverse(bits, d, bits.length - 1);
37         reverse(bits, 0, bits.length - 1);
38     }
39 }

 

Related Problems 

Flip Bits

转载于:https://www.cnblogs.com/lz87/p/7820940.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值