1
+ /* A rotation (or circular shift) is an operation similar to shift except that the
2
+ bits that fall off at one end are put back to the other end.
3
+ In left rotation, the bits that fall off at left end are put back at right end.
4
+ In right rotation, the bits that fall off at right end are put back at left end.
5
+ */
6
+
7
+ #include < bits/stdc++.h>
8
+ using namespace std ;
9
+
10
+ // Left Rotate 'cnt' number of bits of the given number 'n'
11
+ int left_rotate_bits (int n, int cnt)
12
+ {
13
+ int msb;
14
+
15
+ // 32 is the total number of bits used to store an INT variable in C++
16
+ for (cnt = cnt % 31 ;cnt>0 ;cnt--)
17
+ {
18
+ // Store the current MSB in a temporary variable
19
+ msb = (n >> 31 ) & 1 ;
20
+ // Left rotate the given number by one bit
21
+ n = (n<<1 );
22
+ // Set the dropped MSB as the new LSB
23
+ n = n | msb;
24
+ }
25
+ return n;
26
+ }
27
+
28
+ // Right Rotate 'cnt' number of bits of the given number 'n'
29
+ int right_rotate_bits (int n, int cnt)
30
+ {
31
+ int lsb;
32
+
33
+ // 32 is the total number of bits used to store an INT variable in C++
34
+ for (cnt = cnt % 31 ;cnt>0 ;cnt--)
35
+ {
36
+ // Store the current LSB in a temporary variable
37
+ lsb = n & 1 ;
38
+ // Right rotate the given number by one bit and drop its LSB
39
+ n = (n >> 1 ) & (~(1 << 31 ));
40
+ // Set the dropped LSB as the new MSB
41
+ n = n | (lsb << 31 );
42
+ }
43
+ return n;
44
+ }
45
+
46
+
47
+ int main ()
48
+ {
49
+ int n,cnt,left,right;
50
+ cout<<" \n Enter the number : " ;
51
+ cin>>n;
52
+
53
+ cout<<" How many bits do you want to rotate : " ;
54
+ cin>>cnt;
55
+
56
+ // Call the sort function
57
+ left = left_rotate_bits (n, cnt);
58
+ right = right_rotate_bits (n,cnt);
59
+
60
+ cout<<" The Left-rotated number is : " <<left<<endl;
61
+ cout<<" The Right-rotated number is : " <<right<<endl;
62
+
63
+ return 0 ;
64
+ }
65
+
66
+ /*
67
+ INPUT
68
+ Enter the number : 39
69
+ How many bits do you want to rotate : 17
70
+ OUTPUT
71
+ The Left-rotated number is : 5111808
72
+ The Right-rotated number is : 1277952
73
+
74
+ Time Complexity: O(n)
75
+ Space Complexity: O(1)
76
+ */
0 commit comments