Skip to content

Commit bb1cc4e

Browse files
committed
made changes
1 parent 6826e2b commit bb1cc4e

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Coding/copy_set_bits_in_range.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
//Copy set bits in a range
2+
//Given two numbers x and y, and a range [l, r] where 1 <= l, r <= 32. The task is consider set bits of y in range [l, r] and set these bits in x also.
3+
4+
#include <iostream>
5+
using namespace std;
6+
//https://www.geeksforgeeks.org/copy-set-bits-in-a-range/
7+
8+
// Copying set bits in range [left, right] from b to a. Kindly note that a is passed by reference and modified by this function.
9+
void CopyingSetBits(unsigned &a, unsigned b,
10+
unsigned left, unsigned right)
11+
{
12+
if (left < 1 || right > 32)
13+
return ;
14+
15+
// here we get the length of the mask
16+
int maskLength = (1ll<<(right-left+1)) - 1;
17+
18+
// Shifting the mask to the required position
19+
// "&" with b to get the set bits at between left and right in b
20+
int m = ((maskLength)<<(left-1)) & b ;
21+
a = a | m;
22+
}
23+
24+
int main()
25+
{
26+
unsigned a, b, left, right;
27+
cout<<"Enter the value of x and y respectively: ";
28+
cin>>a>>b;
29+
cout<<"Enter the value of left and right respectively: ";
30+
cin>>left>>right;
31+
CopyingSetBits(a, b, left, right);
32+
cout << "Modified x is " << a;
33+
return 0;
34+
}
35+
36+
//Time Complexity: O(r)
37+
//Auxiliary Space: O(1)

0 commit comments

Comments
 (0)