Simple C++ implementation


  • 0
    T
    class Solution {
    private:
        vector<int> convert(string a, int n)
        {
            vector<int> value;
            if(n==0)
                return value;
            value.resize(n);
            int len = a.length();
            int i;
            for(i=0; i<n-len; i++)
                value[i] = 0;
            for(i= n-len; i<n; i++)
                value[i] = (a.at(i-n+len) - '0');
            return value;
        }
    public:
        string addBinary(string a, string b) {
            int n = a.length();
            if(b.length() > n)
                n = b.length();
            vector<int> Aarray;
            vector<int> Barray;
            Aarray = convert(a, n);
            Barray = convert(b, n);
            vector<int> value;
            value.resize(n+1, 0);
            int i;
            for(i=0; i<n; i++)
            {
                if(Aarray[n-1-i] + Barray[n-1-i] + value[n-i] == 0)
                {
                    value[n-i]  = 0;
                }
                else if(Aarray[n-1-i] + Barray[n-1-i] +value[n-i]== 1)
                {
                    value[n-i] = 1;
                }
                else if( Aarray[n-1-i] + Barray[n-1-i] +value[n-i] == 2)
                {
                    value[n-i] = 0;
                    value[n-i-1] = 1;
                }
                else if(Aarray[n-1-i] + Barray[n-1-i] +value[n-i] == 3)
                {
                    value[n-i] = 1;
                    value[n-i-1] = 1;
                }
            }
            string s = "";
            int j;
            for(i=0; i<n+1; i++)
            {
                if(value[i] == 1)
                    break;
            }
           if(i==n+1)
                s = s + '0';
            else
            {
                for(j=i; j<n+1; j++)
                {
                 if(value[j] == 1)
                      s = s +'1';
                 else
                     s = s + '0';
                }
             }
            return s;
        }
    };

Log in to reply
 

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