#二进制乘法 (输入输出皆为二进制)

在讲二进制乘法之前,我们先看下十进制的乘法,比如这个例子:

 

其实乘法就是每一位数乘完之后的结果相加,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;
}

 

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值