Open In App

Bitwise multiplication of Binary Array with K

Last Updated : 21 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array nums[] representing a binary number and integer K, the task is to perform bitwise multiplication by a given integer K (where K is a power of 2). Return a new array representing the product.

Examples:

Input: nums[] = {1, 0, 1},  K = 8

Output: {1, 0, 1, 0, 0, 0}

Explanation: The binary number represented by nums is 101, which is equivalent to the decimal number 5. We need to multiply this number by a power of 2, in this case k=8. Multiplying by a power of 2 is equivalent to shifting the binary representation of the number to the left by the corresponding number of bits. In this case, shifting 101 to the left by 3 bits gives 101000, which is equivalent to the decimal number 40. Therefore, the output array should be [1, 0, 1, 0, 0, 0], which represents the binary number 101000.

Input: nums[] = {1, 0, 1, 1, 0}, K = 4

Output: {1, 0, 1, 1, 0, 0, 0}

Explanation: The binary number represented by nums is 10110, which is equivalent to the decimal number 22. We need to multiply this number by a power of 2, in this case k=4. Multiplying by a power of 2 is equivalent to shifting the binary representation of the number to the left by the corresponding number of bits. In this case, shifting 10110 to the left by 2 bits gives 1011000, which is equivalent to the decimal number 88. Therefore, the output array should be [1, 0, 1, 1, 0, 0, 0], which represents the binary number 1011000.

Approach: To solve the problem follow the below idea:

The intuition behind this approach is based on the fact that multiplying a binary number by a power of 2 is equivalent to shifting the bits of the binary number to the left by the number of positions equal to the exponent of the power of 2. For example, multiplying the binary number 101 by 2^3 (8) is equivalent to shifting the bits of the binary number 3 positions to the left, resulting in the binary number 101000.

To implement this idea, we can first initialize an empty vector to hold the result of the multiplication. We then loop through the binary number from right to left and multiply each bit by the power of 2, keeping track of any carry-over. We insert the least significant bit of the product into the result vector and update the carry-over. Once we have processed all the bits of the binary number, we check if there is any carry-over remaining and insert it into the result vector as well. Finally, we return the result vector.

Below is the implementation of the above approach:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
vector<int> multiply(vector<int>& nums, int k)
{
    vector<int> result;
    int carry = 0;
    for (int i = nums.size() - 1; i >= 0; i--) {
        int prod = nums[i] * k + carry;
        result.insert(result.begin(), prod % 2);
        carry = prod / 2;
    }
    while (carry > 0) {
        result.insert(result.begin(), carry % 2);
        carry /= 2;
    }
    return result;
}
 
// Drivers code
int main()
{
    vector<int> nums = { 1, 0, 1 };
    int k = 8;
    vector<int> result = multiply(nums, k);
    cout << "[";
    for (int i = 0; i < result.size(); i++) {
        cout << result[i];
        if (i != result.size() - 1) {
            cout << ", ";
        }
    }
    cout << "]" << endl;
    cout << endl;
    return 0;
}


Java




// Java code for the above approach:
import java.util.*;
 
class GFG {
    static ArrayList<Integer> multiply(ArrayList<Integer> nums, int k) {
        ArrayList<Integer> result = new ArrayList<>();
        int carry = 0;
        for (int i = nums.size() - 1; i >= 0; i--) {
            int prod = nums.get(i) * k + carry;
            result.add(0, prod % 2);
            carry = prod / 2;
        }
        while (carry > 0) {
            result.add(0, carry % 2);
            carry /= 2;
        }
        return result;
    }
 
    // Driver code
    public static void main(String[] args) {
        ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(1, 0, 1));
        int k = 8;
        ArrayList<Integer> result = multiply(nums, k);
        System.out.print("[");
        for (int i = 0; i < result.size(); i++) {
            System.out.print(result.get(i));
            if (i != result.size() - 1) {
                System.out.print(", ");
            }
        }
        System.out.println("]");
    }
}
// This code is contributed by Tapesh(tapeshdua420)


Python3




# Pythone code for the above approach
def multiply(nums, k):
    result = []
    carry = 0
    for i in range(len(nums) - 1, -1, -1):
        prod = nums[i] * k + carry
        result.insert(0, prod % 2)
        carry = prod // 2
    while carry > 0:
        result.insert(0, carry % 2)
        carry //= 2
    return result
 
# Driver code
nums = [1, 0, 1]
k = 8
result = multiply(nums, k)
print("[", end="")
for i in range(len(result)):
    print(result[i], end="")
    if i != len(result) - 1:
        print(", ", end="")
print("]")


C#




// C# implementation for the above approach
using System;
using System.Collections.Generic;
 
class GFG {
    static List<int> Multiply(List<int> nums, int k)
    {
        List<int> result = new List<int>();
        int carry = 0;
        for (int i = nums.Count - 1; i >= 0; i--) {
            int prod = nums[i] * k + carry;
            result.Insert(0, prod % 2);
            carry = prod / 2;
        }
        while (carry > 0) {
            result.Insert(0, carry % 2);
            carry /= 2;
        }
        return result;
    }
 
    public static void Main(string[] args)
    {
        List<int> nums = new List<int>{ 1, 0, 1 };
        int k = 8;
        List<int> result = Multiply(nums, k);
        Console.Write("[");
        for (int i = 0; i < result.Count; i++) {
            Console.Write(result[i]);
            if (i != result.Count - 1) {
                Console.Write(", ");
            }
        }
        Console.WriteLine("]");
    }
}
 
// This code is contributed by Tapesh(tapeshdua420)


Javascript




// function to multiply k to binary array
function multiply(nums, k) {
 
    // array to hold result of multiplication
    let result = [];
    let carry = 0;
     
    // Loop through the binary array from right to left
    for (let i = nums.length - 1; i >= 0; i--) {
         
        // multiply each bit by power of 2
        let prod = nums[i] * k + carry;
        result.unshift(prod % 2);
         
        // storing carry bit
        carry = Math.floor(prod / 2);
    }
    // if any carry remains insert int result
    while (carry > 0) {
        result.unshift(carry % 2);
        carry = Math.floor(carry / 2);
    }
    return result;
}
 
 
// Driver code
let nums = [1, 0, 1];
let k = 8;
let result = multiply(nums, k);
console.log("[");
for (let i = 0; i < result.length; i++) {
    console.log(result[i]);
    if (i !== result.length - 1) {
        console.log(", ");
    }
}
console.log("]");
console.log();


Output

[1, 0, 1, 0, 0, 0]










Time Complexity: O(n), where n is the size of the input vector nums.
Auxiliary Space: O(n), where n is the size of the output vector result.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads