LeetCode 67 Add Binary(二进制相加)(*)

翻译

给定两个二进制字符串,返回它们的和(也是二进制字符串)。

例如,
a = "11"
b = "1"
返回 "100".

原文

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

分析

我一开始写了这个算法,虽然实现了功能,不过不符合题目的用意。

int ctoi(char c) {
    return (int)c - 48;
}

int pow2(int n) {
    int sum = 1;
    while ((n--) > 0)
        sum *= 2;
    return sum;
}

int btoi(string s) {
    int sum = 0, len = s.size();
    for (int i = 0; i < len; ++i) {
        sum += ctoi(s[i]) * pow2(len - i - 1);
    }
    return sum;
}

string itob(int n) {
    if (n == 0) return "0";
    string s = "";
    while (n >= 1) {
        if (n % 2 == 1)
            s += "1";
        else s += "0";
        n /= 2;
    }
    string newStr = "";
    for (int i = s.size() - 1; i >= 0; i--)
        newStr += s[i];
    return newStr;
}

string addBinary(string a, string b) {
    return itob(btoi(a) + btoi(b));
}

然后改了改,写出这么脑残的代码我自己都醉了……

string addBinary(string a, string b) {
    if (a.size() < b.size()) swap(a, b);
    int len1 = a.size(), len2 = b.size();
    int comLen = len1 < len2 ? len1 : len2;
    int pos = 0;
    string str = "";
    for (int index1 = len1 - 1, index2 = len2 - 1; index1 > len1 - comLen, index2 >= 0; index1--, index2--) {
        if (pos == 0) {
            if (a[index1] == '1' && b[index2] == '1') {
                str += "0";
                pos = 1;
            }
            else if (a[index1] == '0' && b[index2] == '0') {
                str += "0";
            }
            else {
                str += "1";
            }
        }
        else if (pos == 1) {
            if (a[index1] == '1' &&b[index2] == '1') {
                str += "1";
                pos = 1;
            }
            else if (a[index1] == '0' && b[index2] == '0') {
                str += "1";
                pos = 0;
            }
            else {
                str += "0";
                pos = 1;
            }
        }
    }

    for (int index = len1 - comLen-1; index >= 0; index--) {
        if (pos == 0) {
            if (a[index] == '1') {
                str += "1";
            }
            else {
                str += "0";
            }
        }
        else if (pos == 1) {
            if (a[index] == '1') {
                str += "0";
                pos = 1;
            }
            else {
                str += "1";
                pos = 0;
            }
        }
    }
    if (pos == 1) str += "1";
    string newStr = "";
    for (int i = str.size() - 1; i >= 0; i--)
        newStr += str[i];
    return newStr;
}

转了一圈也没发现非常简洁的代码,那就先这样了……

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值