首页 > 其他 > 详细

leetcode No67. Add Binary

时间:2016-08-04 10:33:23      阅读:247      评论:0      收藏:0      [点我收藏+]

Question:

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

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

按位求和

Algorithm:

从后往前加,有三种情况,具体见程序

Accepted Code:

class Solution {
public:
    string addBinary(string a, string b) {
        string res;
        int N1=a.size();
        int N2=b.size();
        int maxlength=N1>N2?N1:N2;
        reverse(a.begin(),a.end());
        reverse(b.begin(),b.end());
        int i=0;
        int sum=0;
        while(i<maxlength)
        {
            if(i<N1&&i<N2)
                sum+=((a[i]-'0')+(b[i]-'0'));
            else if(i<N1&&i>=N2)
                sum+=(a[i]-'0');
            else
                sum+=(b[i]-'0');
            res.push_back(sum%2+'0');
            sum=sum/2;
            i++;
        }
        if(sum>0)
            res.push_back(sum+'0');
        reverse(res.begin(),res.end());
        return res;
    }
};



leetcode No67. Add Binary

原文:http://blog.csdn.net/u011391629/article/details/52115985

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!