67. Add Binary

Add Binary  (C++)

class Solution {

public:
    string addBinary(string a, string b) {
        string ans="";
        int carry=0;
    while(a.size()||b.size())
    {
        int x=0,y=0;
        if(a.size()){
            x=a.back()-'0';
            a.pop_back();
        }
        if(b.size()){
            x+=b.back()-'0';
            b.pop_back();
        }
        
        x+=carry;
        if(x==1){ans+='1';carry=0;}
        if(x==0)ans+='0';
        if(x==2){ans+='0';carry=1;}
        if(x==3){ans+='1';carry=1;}
         }
        if(carry)ans+='1';
        reverse(ans.begin(),ans.end());
        return ans;
    }
};

Comments

Popular posts from this blog

1431. Kids With the Greatest Number of Candies

125. Valid Palindrome

771. Jewels and Stones