-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathrotate_bits.cpp
73 lines (58 loc) · 1.66 KB
/
rotate_bits.cpp
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// C++ program to Rotate a number by a specific bits
#include <bits/stdc++.h>
using namespace std;
// Left Rotate 'cnt' number of bits of the given number 'n'
int left_rotate_bits(int n, int cnt)
{
int msb;
// 32 is the total number of bits used to store an INT variable in C++
for(cnt = cnt % 31;cnt>0;cnt--)
{
//Store the current MSB in a temporary variable
msb = (n >> 31) & 1;
//Left rotate the given number by one bit
n = (n<<1);
//Set the dropped MSB as the new LSB
n = n | msb;
}
return n;
}
// Right Rotate 'cnt' number of bits of the given number 'n'
int right_rotate_bits(int n, int cnt)
{
int lsb;
// 32 is the total number of bits used to store an INT variable in C++
for(cnt = cnt % 31;cnt>0;cnt--)
{
//Store the current LSB in a temporary variable
lsb = n & 1;
//Right rotate the given number by one bit and drop its LSB
n = (n >> 1) & (~(1 << 31));
//Set the dropped LSB as the new MSB
n = n | (lsb << 31);
}
return n;
}
int main()
{
int n,cnt,left,right;
cout<<"\nEnter the number? ";
cin>>n;
cout<<"How many bits do you want to rotate? ";
cin>>cnt;
//Call the sort function
left = left_rotate_bits(n, cnt);
right = right_rotate_bits(n,cnt);
cout<<"The Left-rotated number is: "<<left<<endl;
cout<<"The Right-rotated number is: "<<right<<endl;
return 0;
}
/*
Time Complexity: O(n)
Space Complexity: O(1)
SAMPLE INPUT AND OUTPUT
Enter the number? 39
How many bits do you want to rotate? 17
The Left-rotated number is: 5111808
The Right-rotated number is: 1277952
*/