C++ solution easy understand


  • 0
    L

    ' class Solution {
    public:
    string addBinary(string a, string b) {
    string result="";
    int carry=0;

        int i=a.size()-1;
        int j=b.size()-1;
        while(i>=0||j>=0){
            if(i>=0&&j>=0){
                if(a[i]=='1'&&b[j]=='1'){
                    result=(carry)?("1"+result):("0"+result);
                    carry=1;
                }
                else if(a[i]=='0'&&b[j]=='0'){
                    result=(carry)?("1"+result):("0"+result);
                    carry=0;
                }
                else{
                    result=(carry)?("0"+result):("1"+result);
                    carry=(carry)?1:0;
                }
                i--;
                j--;
            }
            else{
               if(carry==0){
                   result=(a.size()>b.size())?(a.substr(0,i+1)+result):((b.substr(0,j+1)+result));
                   return result;
               } 
               else{
                   char temp=(a.size()>b.size())?a[i]:b[j];
                   if(temp=='1'){
                       result="0"+result;
                       carry=1;
                   }
                   else{
                       result="1"+result;
                       carry=0;
                   }
                   if(i>=0)
                   i--;
                   else
                   j--;
               }
            }
        }
        if(carry)
        result="1"+result;
        return result;
    }
    

    };'


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.