LeetCode67 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"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

题源:here;完整实现:here
思路:
先将ab对齐,然后相加。因为对齐后不需要在循环中再进行判断,所以效率会高一些。代码如下:

class Solution {
public:
    string addBinary(string a, string b) {
        while (a.size() != b.size()){
            if (a.size() > b.size()) b.insert(b.begin(), '0');
            else a.insert(a.begin(), '0');
        }
        int carryBit = 0;
        for (int i = a.size()-1; i >= 0; i--){
            int tSum = a[i] - '0' + b[i] - '0'+carryBit;
            a[i] = tSum % 2 + '0'; carryBit = tSum / 2;
        }
        if (carryBit) a.insert(a.begin(), '1');
        return a;
    }
};

贴出运行结果纪念一下:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/80935776