码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】67. Add Binary 解题小结

时间:2016-09-11 11:33:50      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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);
    }
};

 

【LeetCode】67. Add Binary 解题小结

标签:

原文地址:http://www.cnblogs.com/Doctengineer/p/5861315.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!