File tree 2 files changed +62
-0
lines changed
2 files changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Do Left and Right rotate given the number n and the shift-by value d
2
+ // Number is n
3
+ // The number of bits by which n should be rotated is given by d
4
+ // Both rotate right and rotate left is provided
5
+ // 32 bit frame is taken
6
+
7
+ #include < iostream>
8
+ #include < algorithm>
9
+ using namespace std ;
10
+ #define MAX 32
11
+ int bit_rright (int n, int l)
12
+ {
13
+ int a = n<<(MAX-l);
14
+ int b = n>>l;
15
+ return (a|b);
16
+ }
17
+ int bit_rleft (int n , int l)
18
+ {
19
+ int a = n<<l;
20
+ int b = n>>(MAX-l);
21
+ return (a|b);
22
+ }
23
+
24
+ int main ()
25
+ {
26
+ int n,d;
27
+ cin>>n>>d;
28
+ int x=bit_rright (n,d);
29
+ int y = bit_rleft (n,d);
30
+ cout<<x<<" " <<y<<endl;
31
+ }
Original file line number Diff line number Diff line change
1
+ // Given range l and r for the number n, toggle bits within the range
2
+ // n = 50 -> 110010
3
+ // l = 2
4
+ // r = 5
5
+ // Result -> 101100 = 44
6
+
7
+ #include < iostream>
8
+ #include < algorithm>
9
+ using namespace std ;
10
+
11
+ int toggle (int n , int l , int r)
12
+ {
13
+ int c=0 ;
14
+ int b=1 ; // For a new num, set bits between l to r
15
+ b = b<<(l-1 );
16
+ for (int i=0 ;i<r-l+1 ;i++)
17
+ {
18
+ c = c|b;
19
+ b = b<<1 ;
20
+ }
21
+ int x = c^n; // XOR with the original number to reverse the bits
22
+ return x;
23
+ }
24
+
25
+ int main ()
26
+ {
27
+ int n,l,r;
28
+ cin>>n>>l>>r;
29
+ int x = toggle (n,l,r);
30
+ cout<<x<<endl;
31
+ }
You can’t perform that action at this time.
0 commit comments