Add Binary

ㅋㅋ·2023년 2월 14일
0

알고리즘-leetcode

목록 보기
111/135

이진수로 이루어진 문자열 a와 b를 받고, 이진수를 더하여 이진수 문자열로 반환하는 문제

class Solution {
public:
    string addBinary(string a, string b) {
        
        string longer{};
        string shorter{};

        if (a.size() < b.size())
        {
            longer = std::move(b);
            shorter = std::move(a);
        }
        else
        {
            longer = std::move(a);
            shorter = std::move(b);
        }

        auto longIter = longer.rbegin();
        auto shortIter = shorter.rbegin();

        bool carry{false};
        while (shortIter != shorter.rend())
        {
            if (carry)
            {
                ++(*longIter);
                carry = false;
            }

            *longIter += (*shortIter - '0');
            if ('2' <= *longIter)
            {
                *longIter -= 2;
                carry = true;
            }

            ++longIter;
            ++shortIter;
        }

        while (longIter != longer.rend() && carry)
        {
            if (carry)
            {
                ++(*longIter);
                carry = false;
            }

            if ('2' <= *longIter)
            {
                *longIter -= 2;
                carry = true;
            }

            ++longIter;
        }

        if (carry)
        {
            return "1" + longer;
        }

        return longer;
    }
};

0개의 댓글