67. Add Binary

Problem

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

Input: a = "11", b = "1"
Output: "100"
Input: a = "1010", b = "1011"
Output: "10101"

Code

static int var = [](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    string addBinary(string a, string b) {
        string res = "";
        int a_z = a.size();
        int b_z = b.size();
        if (a_z<b_z) {
            for (int i = 0; i<b_z - a_z; i++)
                a = "0" + a;
        }
        else {
            for (int i = 0; i<a_z - b_z; i++) {
                b = "0" + b;
            }
        }
        bool flag = false;
        for (int i = a.size() - 1; i >= 0; i--) {
            if (a[i] == '1' && b[i] == '1') {
                if (flag)
                    res = "1" + res;
                else
                    res = "0" + res;
                flag = true;
            }
            else if (a[i] == '0' && b[i] == '0') {
                if (flag)
                    res = "1" + res;
                else
                    res = "0" + res;
                flag = false;
            }
            else {
                if (flag)
                    res = "0" + res;
                else
                    res = "1" + res;
            }
        }
        if (flag)
            res = "1" + res;
        return res;
    }
};

Result

67. Add Binary.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 今天状态不错,运动后有重生的感觉。请相信:劫难过后,必有重生。
    早菲儿阅读 165评论 0 0
  • lol最近的活动 英雄联盟作为近几年来最火的游戏,最近也是推出了不少的活动。 像是最近的召唤师招募令: 还有3月份...
    文学社社长阅读 374评论 0 3
  • 想要年薪几十万并不难,关键看你怎么做,手上的资源有多少。现实是,没有任何资源和人脉的人很难在某方面达到一定的成就。...
    笨笨的鱼儿阅读 427评论 0 1