首页 > 代码库 > HappyLeetcode37:Add Binary

HappyLeetcode37: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 lengtha = a.length();        int lengthb = b.length();        int indexa = a.length() - 1;        int indexb = b.length() - 1;        int res = 0;//设置进位        string result;        map<char, int> mapping;        mapping[1] = 1;        mapping[0] = 0;        int value;        while (indexa>=0||indexb>=0)        {                        if (indexa < 0)                value = 0 + mapping[b[indexb]] + res;            else if (indexb < 0)                value = mapping[a[indexa]] + 0 + res;            else                value = mapping[a[indexa]] + mapping[b[indexb]] + res;            if (value >= 2)            {                res = 1;                value %=2;            }            else            {                res = 0;            }            result.push_back(value+0-0);            indexa--;            indexb--;        }        if (res == 1)            result.push_back(res + 0 - 0);        reverse(result.begin(), result.end());        return result;    }};

HappyLeetcode37:Add Binary