[leetcode] 【字符串】 67. Add Binary

来源:互联网 发布:淘宝图片拍摄技巧 编辑:程序博客网 时间:2024/05/16 10:02

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

For example,
a = "11"
b = "1"
Return "100".

题意

两个字符串表示两个二进制数,返回二进制的字符串表示他们的和。

题解

我是先翻转再操作,这样可以从下标0开始操作。
注意长度,以及最后进位。

class Solution {public:    string addBinary(string a, string b) {        const int n=a.size()>b.size() ? a.size() :b.size();        reverse(a.begin(),a.end());//翻转字符串,方便从低位开始操作        reverse(b.begin(),b.end());        string res;        int carry=0;        for(int i=0;i<n;i++)        {            const int ai=i<a.size() ? a[i]-'0':0;            const int bi=i<b.size() ? b[i]-'0':0;            const int val=(ai+bi+carry)%2;            res.insert(res.begin(),val+'0');            carry=(ai+bi+carry)/2;                    }        if(carry==1)            res='1'+res;        return res;    }};



0 0