Add Binary

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Add Binary相关的知识,希望对你有一定的参考价值。

问题描写叙述:Given two binary strings, return their sum (also a binary string).

For example,
a = “11”
b = “1”
Return “100”.
解决方式:

class Solution {
public:
    string addBinary(string a, string b) {
        int aLen = a.size();
        int bLen = b.size();
        int i = aLen-1;
        int j = bLen-1;
        int c = 0;
        int num;
        string result;
        while(i>=0&&j>=0)
        {
            num = a[i]-‘0‘+b[j]-‘0‘+c;
            c = num/2;
            num = num%2;
            result = char(num+‘0‘)+result;//此处的想法比較关键,用一个字符串的加法从后向前加入字符。
            i--;
            j--;
        }
        while(i>=0)
        {
            num = char(a[i]-‘0‘)+c;
            c = num/2;
            num=num%2;
            result = char(num+‘0‘)+result;
            i--;
        }
        while(j>=0)
        {
            num =b[j]-‘0‘+c;
            c = num/2;
            num=num%2;
            result = char(num+‘0‘)+result;
            j--;
        }
        if(c>0)
        {
            result = ‘1‘+result;
        }
        return result;
    }
};

以上是关于Add Binary的主要内容,如果未能解决你的问题,请参考以下文章

leetcode add_binary 采坑记

leetcode67. Add Binary

leetcode Add Binary (easy) /java

leetcode第一刷_Add Binary

Add Binary

67. Add Binary