美文网首页
LeetCode 67. Add Binary

LeetCode 67. Add Binary

作者: cb_guo | 来源:发表于2019-04-09 15:03 被阅读0次

    题目描述

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

    The input strings are both non-empty and contains only characters 1 or 0.

    Example 1:

    Input: a = "11", b = "1"
    Output: "100"
    

    Example 2:

    Input: a = "1010", b = "1011"
    Output: "10101"
    

    题目思路

    • 思路一、看高赞得到的答案,真是清晰易懂啊
    class Solution {
    public:
        string addBinary(string a, string b) {
            string result = "";
            
            int i = a.size() - 1;
            int j = b.size() - 1;
            int sum = 0;
            
            while(i >= 0 || j >= 0){
                if(i >= 0)  sum += a[i--] - '0';
                
                if(j >= 0)  sum += b[j--] - '0';
                
                result.insert(0, to_string(sum%2));
                sum /= 2;
            }
            
            if(sum)  result.insert(0, "1");
            
            return result;
        }
    };
    

    总结展望

    相关文章

      网友评论

          本文标题:LeetCode 67. Add Binary

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