67. 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"

 

解题思路:

我原来的代码巨长无比(就是正常的思路)

想看看有没有人又简短的代码

我就知道,一定有。

参考:Short code by c++

 

代码

class Solution {
public:
    string addBinary(string a,string b) {
        int len1 = a.size();
        if(len1 == 0) return b;
        int len2 = b.size();
        if(len2 == 0) return a;
        
        int c = 0,i = len1-1,j = len2-1;
        string s;
        while(c > 0 || i > -1 || j > -1){
            c += i > -1 ? a[i--] - 0 : 0;
            c += j > -1 ? b[j--] - 0 : 0;
            s.push_back(char(c%2 + 0));
            c =  c/2;
        }
        reverse(s.begin(),s.end());
        return s;
    }
};

相关文章

自1998年我国取消了福利分房的政策后,房地产市场迅速开展蓬...
文章目录获取数据查看数据结构获取数据下载数据可以直接通过...
网上商城系统MySql数据库设计
26个来源的气象数据获取代码
在进入21世纪以来,中国电信业告别了20世纪最后阶段的高速发...