[leetcode]Add Binary

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

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

分析:

二进制求和,可以新定义一个string,用一个int型carry表示进位。从字符串末尾开始相加,若carry为2,则向新字符串里开头位置添0,carry置1;若carry小于2,则向新字符串里开头位置添carry的值。遍历完a、b较长的字符串并且carry等于0为止。此外要注意字符串与int型之间的转换。

class Solution {
public:
    string addBinary(string a, string b) {
        int len1 = a.size();
        int len2 = b.size();
        int carry = 0;//初始进位为0
        string c = "";
        int i = len1-1;
        int j = len2-1;
        if(len1 == 0)
            return b;
        if(len2 == 0)
            return a;
        while(i >= 0 || j >= 0 || carry > 0)
        {
            if(i >= 0)
            {
                carry += a[i] - '0';
                i--;
            }
            if(j >= 0)
            {
                carry += b[j] - '0';
                j--;
            }
            c.insert(c.begin(),carry % 2 + '0');//在c的开始位置插入低位求和的结果
            carry /= 2;//若和为2,则进位为1
        }
        return c;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41814716/article/details/83926931
今日推荐