We are given two numbers n and m, and two-bit positions, i and j. Insert bits of m into n starting from j to i. We can assume that the bits j through i have enough space to fit all of m. That is, if m = 10011, you can assume that there are at least 5 bits between j and i. You would not, for example, have j = 3 and i = 2, because m could not fully fit between bit 3 and bit 2.
Input : n = 1024 m = 19 i = 2 j = 6; Output : n = 1100 Binary representations of input numbers m in binary is (10011)2 n in binary is (10000000000)2 Binary representations of output number (10000000000)2 Input : n = 5 m = 3 i = 1 j = 2 Output : 7
1. Clear the bits j through i in n 2. Shift m so that it lines up with bits j through i 3. Return Bitwise AND of m and n.
The trickiest part is Step 1. How do we clear the bits in n? We can do this with a mask. This mask will have all 1s, except for 0s in the bits j through i. We create this mask by creating the left half of the mask first, and then the right half.
Following is the implementation of the above approach.
1100 // in Binary (10001001100)2
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Inserting M into N such that m starts at bit j and ends at bit i | Set-2
- Find the count of distinct numbers in a range
- Convert Decimal To Hexa-Decimal including negative numbers
- Find a number X such that (X XOR A) is minimum and the count of set bits in X and B are equal
- Set, Clear and Toggle a given bit of a number in C
- Find extra element in the second array
- Maximum number of consecutive 1's in binary representation of all the array elements
- Maximum frequency of a remainder modulo 2i
- Maximum Sum of Products of two arrays by toggling adjacent bits
- Maximum Bitwise OR pair from a range
- Find closest integer with the same weight
- Rearrange array elements such that Bitwise AND of first N - 1 elements is equal to last element
- Number of ways to split a binary number such that every part is divisible by 2
- Longest subsequence with a given AND value | O(N)
Improved By : jit_t