首页 > 其他 > 详细

Add Binary

时间:2014-07-11 20:04:42      阅读:336      评论: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 sol;
        int len1=a.size();
        int len2=b.size();
        std::reverse(a.begin(),a.end());
        std::reverse(b.begin(),b.end());
        int i=0;
        int carry=0;
        while(i<len1&&i<len2)
        {
            int c=(a[i]-0+b[i]-0+carry)%2;
            carry=(a[i]-0+b[i]-0+carry)/2;
            sol.append(1,c+0);
            i++;
        }
        while(i<len1)
        {
            int c=(a[i]-0+carry)%2;
            carry=(a[i]-0+carry)/2;
            sol.append(1,c+0);
            i++;
        }
        while(i<len2)
        {
            int c=(b[i]-0+carry)%2;
            carry=(b[i]-0+carry)/2;
            sol.append(1,c+0);
            i++;
        }
        if(carry!=0)sol.append(1,1);
        std::reverse(sol.begin(),sol.end());
        return sol;
        
    }
};
class Solution {
public:
    string addBinary(string a, string b) {
        string sol;

        if(b.size()>a.size())
        {
            string t=a;
            a=b;
            b=t;
        }
        int len1=a.size();
        int len2=b.size();
        std::reverse(a.begin(),a.end());
        std::reverse(b.begin(),b.end());
        int i=0;
        int carry=0;
        while(i<len2)
        {
            int c=(a[i]-0+b[i]-0+carry)%2;
            carry=(a[i]-0+b[i]-0+carry)/2;
            sol.append(1,c+0);
            i++;
        }
        while(i<len1)
        {
            int c=(a[i]-0+carry)%2;
            carry=(a[i]-0+carry)/2;
            sol.append(1,c+0);
            i++;
        }
       
        if(carry!=0)sol.append(1,1);
        std::reverse(sol.begin(),sol.end());
        return sol;
        
    }
};
class Solution {
public:
    string addBinary(string a, string b) {
        string sol;

        if(b.size()>a.size())
        {
            string t=a;
            a=b;
            b=t;
        }
        int len1=a.size();
        int len2=b.size();
        std::reverse(a.begin(),a.end());
        std::reverse(b.begin(),b.end());
        int i=0;
        int carry=0;
        while(i<len2)
        {
            int c=(a[i]-0+b[i]-0+carry)%2;
            carry=(a[i]-0+b[i]-0+carry)/2;
            sol.append(1,c+0);
            i++;
        }
        while(i<len1)
        {
            int c=(a[i]-0+carry)%2;
            carry=(a[i]-0+carry)/2;
            sol.append(1,c+0);
            i++;
        }
       
        if(carry!=0)sol.append(1,1);
        std::reverse(sol.begin(),sol.end());
        return sol;
        
    }
};

 

Add Binary,布布扣,bubuko.com

Add Binary

原文:http://www.cnblogs.com/hicandyman/p/3833445.html

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