LeetCode(67) Add Binary

题目

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

For example,
a = “11”
b = “1”
Return “100”.

分析

一个简单的字符串相加,该题目要注意两点:

  1. 字符位的求和计算,必须转换为整型,即:
    如下利用‘0’字符作为中间转换,才得到正确结果。

    int temp = (a[i]-'0') + (b[i]-'0');
    
    char c = temp + '0';
  2. 进位保存于计算

AC代码

class Solution {
public:
    string addBinary(string a, string b) {
        //首先,求得两个字符串的长度
        int la = strlen(a.c_str());
        int lb = strlen(b.c_str());

        //若其中一个字符串为空,直接返回另一个字符串即可
        if (la == 0)
            return b;
        else if (lb == 0)
            return a;

        //保存进位
        int carry = 0 ;
        //保存结果
        string r = la > lb ? a : b ;
        int k = la > lb ? la - 1 : lb - 1;
        //循环变量
        int ia = la - 1, ib = lb - 1;
        for (; ia >= 0 && ib >= 0; --ia, --ib)
        { 
            //转换为整数计算
            int temp = (a[ia] - '0') + (b[ib] - '0') + carry;
            if (temp >= 2)
            {
                temp -= 2;
                carry = 1;
            }
            else{
                carry = 0;
            }//if
            //保存结果为相应字符类型
            r[k] = temp + '0';
            --k;
        }//while

        while (ia >= 0)
        {
            int temp = (a[ia] - '0') + carry;
            if (temp >= 2)
            {
                temp -= 2;
                carry = 1;
            }
            else{
                carry = 0;
            }//if
            r[k] = temp + '0';
            --ia;
            --k;
        }//while

        while (ib >= 0)
        {
            int temp = (b[ib] - '0') + carry;
            if (temp >= 2)
            {
                temp -= 2;
                carry = 1;
            }
            else{
                carry = 0;
            }//if
            r[k] = temp + '0';
            --ib;
            --k;
        }

        //若首位也有进位,则用"1"链接
        if (carry == 0)
            return r;
        else{
            return "1"+r;
        }

    }
};

GitHub测试程序源码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值