Inserting M into N such that m starts at bit j and ends at bit i | Set-2

Given two 32-bit numbers, N and M, and two-bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all of M. Assuming index start from 0.
Examples:Â Â
a) N = 1024 (10000000000),
M = 19 (10011),
i = 2, j = 6
Output : 1100 (10001001100)
b) N = 1201 (10010110001)
M = 8 (1000)
i = 3, j = 6
Output: 1217 (10011000001)
This problem has been already discussed in the previous post. In this post, a different approach is discussed.Â
Approach: The idea is very straightforward, following is the stepwise procedure – Â
- Capture all the bits before i in N, that is from i-1 to 0.
- We don’t want to alter those bits so we will capture them and use later
- Clear all bits from j to 0
- Insert M into N at position j to i
- Insert captured bits at their respective position ie. from i-1 to 0
Let’s try to solve example b for a clear explanation of the procedure.
Capturing bits i-1 to 0 in N:
Create a mask whose i-1 to 0 bits are 1 and rest are 0. Shift 1 to i position in left and subtract 1 from this to get a bit mask having i-1 to 0 bits set. Â
capture_mask = ( 1 << i ) - 1
So for example b, mask will be – Â
capture_mask = ( 1 << 3 ) - 1 Now capture_mask = 1(001)
Now AND this mask with N, i-1 to 0 bits will remain same while rest bits become 0. Thus we are left with i-1 to 0 bits only. Â
captured_bits = N & capture_mask
for example b, captured bits will be –Â
captured_bits = N & capture_mask Now capture_mask = 1 (001)
Clearing bits from j to 0 in N:
Since bits have been captured, clear the bits j to 0 without losing bits i-1 to 0. Create a mask whose j to 0 bits are 0 while the rest are 1. Create such mask by shifting -1 to j+1 position in left. Â
clear_mask = -1 << ( j + 1 )
Now to clear bits j to 0, AND mask with N. Â
N &= clear_mask
For example b will be:Â
N &= clear_mask Now N = 1152 (10010000000)
Inserting M in N:
Now because N has bits from j to 0 cleared, just fit in M into N and shift M i position to left to align the MSB of M with position j in N. Â
M <<= i
For example b-Â Â
M <<= 3 Now M = 8 << 3 = 64 (1000000)
Do a OR of M with N to insert M at desired position. Â
N |= M
For example b –Â
N |= M Now N = 1152 | 64 = 1216 (10011000000)
Inserting captured bits into N:
Till now M has been inserted into N. Now the only thing left is merging back the captured bits at position i-1 to 0. This can be simply done by OR of N and captured bits – Â
N |= captured_bits
For example b – Â
N |= captured_bits N = 1216 | 1 = 1217 (10011000001)
So finally after insertion, the below bitset is obtained.Â
N(before) = 1201 (10010110001) N(after) = 1201 (10011000001)
Below is the implementation of the above approach:
Â
C++
// C++ program to insert 32-bit number// M into N using bit magic#include <bits/stdc++.h>using namespace std;Â
// print binary representation of nvoid bin(unsigned n){Â Â Â Â if (n > 1)Â Â Â Â Â Â Â Â bin(n / 2);Â Â Â Â printf("%d", n % 2);}Â
// Insert m into nint insertion(int n, int m, int i, int j){Â Â Â Â int clear_mask = -1 << (j + 1);Â Â Â Â int capture_mask = (1 << i) - 1;Â
    // Capturing bits from i-1 to 0    int captured_bits = n & capture_mask;Â
    // Clearing bits from j to 0    n &= clear_mask;Â
    // Shifting m to align with n    m = m << i;Â
    // Insert m into n    n |= m;Â
    // Insert captured bits    n |= captured_bits;Â
    return n;}Â
// Driver Codeint main(){Â
    // print original bitset    int N = 1201, M = 8, i = 3, j = 6;    cout << "N = " << N << "(";    bin(N);    cout << ")"         << "\n";Â
    // print original bitset    cout << "M = " << M << "(";    bin(M);    cout << ")"         << "\n";Â
    // Call function to insert M to N    N = insertion(N, M, i, j);    cout << "After inserting M into N from 3 to 6"         << "\n";Â
    // Print the inserted bitset    cout << "N = " << N << "(";    bin(N);    cout << ")"         << "\n";    return 0;} |
Java
// Java program to insert// 32-bit number M into N// using bit magicimport java.io.*;Â
class GFG{Â Â Â Â Â // print binary // representation of nstatic void bin(long n){Â Â Â Â if (n > 1)Â Â Â Â Â Â Â Â bin(n / 2);Â Â Â Â System.out.print(n % 2);}Â
// Insert m into nstatic int insertion(int n, int m, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int i, int j){Â Â Â Â int clear_mask = -1 << (j + 1);Â Â Â Â int capture_mask = (1 << i) - 1;Â
    // Capturing bits from i-1 to 0    int captured_bits = n & capture_mask;Â
    // Clearing bits from j to 0    n &= clear_mask;Â
    // Shifting m to align with n    m = m << i;Â
    // Insert m into n    n |= m;Â
    // Insert captured bits    n |= captured_bits;Â
    return n;}Â
// Driver Codepublic static void main (String[] args) {    // print original bitset    int N = 1201, M = 8, i = 3, j = 6;    System.out.print("N = " + N + "(");    bin(N);    System.out.println(")");         // print original bitset    System.out.print("M = " + M + "(");    bin(M);    System.out.println(")");         // Call function to insert M to N    N = insertion(N, M, i, j);    System.out.println( "After inserting M " +                         "into N from 3 to 6");         // Print the inserted bitset    System.out.print("N = " + N + "(");    bin(N);    System.out.println(")");}}Â
// This code is contributed // by inder_verma. |
Python3
# Python 3 program to insert 32-bit number # M into N using bit magicÂ
# insert M into Ndef insertion(n, m, i, j):Â
    clear_mask = -1 << (j + 1)    capture_mask = (1 << i) - 1Â
    # Capturing bits from i-1 to 0    captured_bits = n & capture_mask Â
    # Clearing bits from j to 0    n &= clear_maskÂ
    # Shifting m to align with n    m = m << iÂ
    # Insert m into n    n |= m Â
    # Insert captured bits    n |= captured_bitsÂ
    return nÂ
# Driverdef main():Â Â Â Â N = 1201; M = 8; i = 3; j = 6Â Â Â Â print("N = {}({})".format(N, bin(N)))Â Â Â Â print("M = {}({})".format(M, bin(M)))Â Â Â Â N = insertion(N, M, i, j)Â Â Â Â print("***After inserting M into N***")Â Â Â Â print("N = {}({})".format(N, bin(N)))Â
if __name__ == '__main__':Â Â Â Â main() |
C#
// C# program to insert// 32-bit number M into N// using bit magicusing System;Â
class GFG{Â Â Â Â Â // print binary // representation of nstatic void bin(long n){Â Â Â Â if (n > 1)Â Â Â Â Â Â Â Â bin(n / 2);Â Â Â Â Console.Write(n % 2);}Â
// Insert m into nstatic int insertion(int n, int m, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int i, int j){Â Â Â Â int clear_mask = -1 << (j + 1);Â Â Â Â int capture_mask = (1 << i) - 1;Â
    // Capturing bits from i-1 to 0    int captured_bits = n & capture_mask;Â
    // Clearing bits from j to 0    n &= clear_mask;Â
    // Shifting m to align with n    m = m << i;Â
    // Insert m into n    n |= m;Â
    // Insert captured bits    n |= captured_bits;Â
    return n;}Â
// Driver Codestatic public void Main (String []args) {    // print original bitset    int N = 1201, M = 8, i = 3, j = 6;    Console.Write("N = " + N + "(");    bin(N);    Console.WriteLine(")");         // print original bitset    Console.Write("M = " + M + "(");    bin(M);    Console.WriteLine(")");         // Call function to     // insert M to N    N = insertion(N, M, i, j);    Console.WriteLine("After inserting M " +                       "into N from 3 to 6");         // Print the inserted bitset    Console.Write("N = " + N + "(");    bin(N);    Console.WriteLine(")");}}Â
// This code is contributed// by Arnab Kundu |
PHP
<?php // PHP program to insert 32-bit number// M into N using bit magicÂ
// print binary representation of nfunction bin($n){Â Â Â Â if ($n > 1)Â Â Â Â Â Â Â Â bin($n / 2);Â Â Â Â echo $n % 2;}Â
// Insert m into nfunction insertion($n, $m, $i, $j){Â Â Â Â $clear_mask = -1 << ($j + 1);Â Â Â Â $capture_mask = (1 << $i) - 1;Â
    // Capturing bits from i-1 to 0    $captured_bits = $n & $capture_mask;Â
    // Clearing bits from j to 0    $n &= $clear_mask;Â
    // Shifting m to align with n    $m = $m << $i;Â
    // Insert m into n    $n |= $m;Â
    // Insert captured bits    $n |= $captured_bits;Â
    return $n;}Â
// Driver CodeÂ
// print original bitset$N = 1201;$M = 8;$i = 3;$j = 6;echo "N = " . $N ."(";bin($N);echo ")" ."\n";Â
// print original bitsetecho "M = " . $M ."(";bin($M);echo ")". "\n";Â
// Call function to insert M to N$N = insertion($N, $M, $i, $j);echo "After inserting M into N " .              "from 3 to 6" ."\n";Â
// Print the inserted bitsetecho "N = " . $N . "(";bin($N);echo ")". "\n";Â
// This code is contributed // by ChitraNayal?> |
Javascript
<script>// Javascript program to insert// 32-bit number M into N// using bit magic         // print binary // representation of n    function bin(n)    {        if (n > 1)            bin(Math.floor(n / 2));        document.write(n % 2);    }         // Insert m into n    function insertion(n,m,i,j)    {        let clear_mask = -1 << (j + 1);    let capture_mask = (1 << i) - 1;       // Capturing bits from i-1 to 0    let captured_bits = n & capture_mask;       // Clearing bits from j to 0    n &= clear_mask;       // Shifting m to align with n    m = m << i;       // Insert m into n    n |= m;       // Insert captured bits    n |= captured_bits;       return n;    }         // Driver Code         // print original bitset    let N = 1201, M = 8, i = 3, j = 6;    document.write("N = " + N + "(");    bin(N);    document.write(")<br>");           // print original bitset    document.write("M = " + M + "(");    bin(M);    document.write(")<br>");           // Call function to insert M to N    N = insertion(N, M, i, j);    document.write( "After inserting M " +                         "into N from 3 to 6<br>");           // Print the inserted bitset    document.write("N = " + N + "(");    bin(N);    document.write(")<br>");               // This code is contributed by rag2127</script> |
N = 1201(10010110001) M = 8(1000) After inserting M into N from 3 to 6 N = 1217(10011000001)
Â
Time complexity: O(log(M)+log(N))=O(log(M*N)
Auxiliary space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



