HappyLeetcode37:Add Binary

4496 ワード

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;

    }

};