forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRotateBits.java
34 lines (30 loc) · 992 Bytes
/
RotateBits.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package me.ramswaroop.bits;
/**
* Created by IntelliJ IDEA.
*
* @author: ramswaroop
* @date: 6/8/15
* @time: 5:12 PM
* <p/>
* 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.
* <p/>
* For example, 000…11100101 becomes 00..0011100101000 if the number
* is rotated 3 times towards left and becomes 101000..0011100 if the
* number is rotated 3 times towards right.
*/
public class RotateBits {
public static int leftRotateBits(int n, int times) {
return n << times | n >>> (32 - times);
}
public static int rightRotateBits(int n, int times) {
return n >>> times | n << (32 - times);
}
public static void main(String a[]) {
System.out.println(leftRotateBits(5, 3));
System.out.println(leftRotateBits(234324, 3));
System.out.println(rightRotateBits(5, 3));
System.out.println(rightRotateBits(234324, 3));
}
}