LeetCode67. Add Binary 解题小结

Posted 医生工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode67. 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) {
       string res(a.size()+b.size(),0);
       int i = a.size()-1;
       int j = b.size()-1;
       int k = res.size()-1;
       int carry = 0;
       
       while(i >= 0 || j >= 0 || carry){
           int sum = 0;
           if (i >= 0) sum += a[i--] - 0;
           if (j >= 0) sum += b[j--] - 0;
           if (carry) sum += carry;
           res[k--] = 0 + (sum%2);
           carry = sum / 2;
       }
       
        std::size_t pos = res.find_first_not_of(0);
        return pos == std::string::npos ? "0":res.substr(pos);
    }
};

 

以上是关于LeetCode67. Add Binary 解题小结的主要内容,如果未能解决你的问题,请参考以下文章

leetcode67. Add Binary

14.leetcode67_add_binary

LeetCode----67. Add Binary(java)

leetcode67. Add Binary

LeetCode 67. Add Binary

*Leetcode 67. Add Binary