Multiplying Binary

Solved
Last edited on
What's this additional variable "addition_result"?

Shift and add is a running sum in the result.

Hope this helps.
Original post:

I am trying to implement an algorithm for multiplying two binary numbers (represented as vectors of their digits, where the least significant bit is the 0th element and the most significant bit is the last element, and num1 >= num2 > 0). The idea is that I should first initialize the result vector that I will be returning, then iterating over the length of num2. In that loop, I should first be multiplying the result by 2, which in binary can be done by adding a zero, then checking if num2[i] = 1. If so, I'm trying to say that result = result + num1, and then outside the loop, returning result. However, this is not working and I'm not sure how to go about fixing it. (It should also be noted that the rest of my code is working according to the debugger and the call to this function is correct.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
vector<int> multiply(vector<int> num1, vector<int> num2)
{
    vector<int> result;
	int carry=0;
	for(int i = 0; i < num2.size(); i++)
	{
		cout << "In this again." << endl;
		cout << "Result before insert: [";
		for(int l = 0; l < result.size(); l++)
		{
			if (l>0)
				cout << ", ";
			cout << result[l];
		}
		cout << "]" << endl;
		result.insert(result.begin(), 0);
		cout << "Result after insert: [";
		vector<int> addition_result;
		for(int l = 0; l < result.size(); l++)
		{
			if (l>0)
				cout << ", ";
			cout << result[l];
		}
		cout << "]" << endl;
		if(num2[i]==1)
		{
			cout << "In the addition process." << endl;
			int sum=0;
			for(int j = 0; j < num1.size(); j++)
			{
				sum = 0;
				if(num1[j] + num2[j] + carry == 0){
					sum = 0;
					carry = 0;
					addition_result.push_back(sum);
				}else if(num1[j] + num2[j] + carry == 1){
					sum = 1;
					carry = 0;
					addition_result.push_back(sum);
				}else if(num1[j] + num2[j] + carry == 2){
					sum = 0;
					carry = 1;
					addition_result.push_back(sum);
				}else if(num1[j] + num2[j] + carry == 3){
					sum = 1;
					carry = 1;
					addition_result.push_back(sum);
				if (carry == 1)
					result.push_back(1);
				}
			}
		}
		result = addition_result;
	}
	return result;	
}

Topic archived. No new replies allowed.