在讲二进制乘法之前,我们先看下十进制的乘法,比如这个例子:
其实乘法就是每一位数乘完之后的结果相加,136 + 170 = 306, 二进制也是一样的,其实进制只是一种表现形式而已,原理都没啥差别。
具体题目可以看下这道https://ac.nowcoder.com/acm/contest/945/J
AC代码 :
#include<bits/stdc++.h>
using namespace std;
string a = "";
void jia (string b) {
if (a.size() < b.size()) {
string ch = "";
for (int i = b.size() - a.size() - 1; i >= 0; i--) ch += "0";
ch += a;
a = ch;
}
else if (a.size() > b.size()) {
string ch = "";
for (int i = a.size() - b.size() - 1; i >= 0; i--) ch += "0";
ch += b;
b = ch;
}
int flag = 0;
for (int i = a.size() - 1; i >= 0; i--) {
int ai = a[i] - '0', bi = b[i] - '0';
if (!flag) {
if (ai + bi == 2) {flag = 1, a[i] = '0';}
else if (ai + bi == 1) {flag = 0, a[i] = '1';}
else {flag = 0, a[i] = '0';}
}
else {
if (ai + bi + 1 == 3) {flag = 1, a[i] = '1';}
else if (ai + bi + 1 == 2) {flag = 1, a[i] = '0';}
else if (ai + bi + 1 == 1) {flag = 0, a[i] = '1';}
}
}
if (flag) {string ss = "1"; ss += a, a = ss;}
}
int main()
{
string line, s = "10001", ch = "", ss = "", t;
cin >> line;
for (int i = s.size() - 1; i >= 0; i--) {
t = "";
for (int j = line.size() - 1; j >= 0; j--) {
if (s[i] == '0' || line[j] == '0') t += '0';
else t += '1';
}
string str = ch;
str += t;
ch += "0";
reverse (str.begin(), str.end());
jia (str);
}
cout << a << endl;
return 0;
}