美文网首页
30. Add Binary FROM Leetcode

30. Add Binary FROM Leetcode

作者: 时光杂货店 | 来源:发表于2017-03-17 16:00 被阅读2次

题目

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

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

频度: 4

解题之法

class Solution
{
public:
    string addBinary(string a, string b)
    {
        string s = "";
        
        int c = 0, i = a.size() - 1, j = b.size() - 1;
        while(i >= 0 || j >= 0 || c == 1)
        {
            c += i >= 0 ? a[i --] - '0' : 0;
            c += j >= 0 ? b[j --] - '0' : 0;
            s = char(c % 2 + '0') + s;
            c /= 2;
        }
        
        return s;
    }
};

相关文章

网友评论

      本文标题:30. Add Binary FROM Leetcode

      本文链接:https://www.haomeiwen.com/subject/xuienttx.html