Add Binary

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

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

很简单的题,代码写麻烦了。注意string加的顺序。

class Solution {
public:
    string addBinary(string a, string b) {
        int la = a.length()-1;
        int lb = b.length()-1;
        string re;
        int flag = 0;
        while(la >= 0 && lb >= 0)
        {
            if(a[la] == '1' && b[lb] == '1')
            {
                if(flag == 1)
                re = "1" + re;
                else
                re = "0" + re;
                flag = 1;
                la--;
                lb--;
                continue;
            }
            if(a[la] == '1' || b[lb] == '1')
            {
                if(flag == 1)
                {
                    re = "0" + re;
                    flag = 1;
  
                }
                else
                {
                    re = "1" + re;
                    flag = 0;
                }
                la--;
                lb--;
                continue;
            }
            if(a[la] == '0' || b[lb] == '0')
            {
                if(flag==0) re = "0"+re;
                else re = "1" +re;
                flag=0;
                la--;
                lb--;
                continue;
            }
        }
        while(la >=0)
        {
            if(a[la] == '1' && flag == 1)
            {
                re = "0" +re;
            }
            else if(a[la] == '0' && flag == 0)
            {
                re = "0" +re;
                flag = 0;
            }
            else {re ="1" +re;flag = 0;}
            la--;
        }
        while(lb >=0)
        {
            if(b[lb] == '1' && flag == 1)
            {
                re = "0" +re;
            }
            else if(b[lb] == '0' && flag == 0)
            {
                re = "0" +re;
                flag = 0;
            }
            else {re ="1" +re;flag = 0;}
            lb--;
        }
        if(flag == 1) re = "1"+re;
        return re;
        
    }
};

  

posted on 2014-03-01 14:33  pengyu2003  阅读(145)  评论(0编辑  收藏  举报

导航