Keep getting runtime errors.


  • 0
    G

    This code I made keeps getting a runtime error and i'm not sure how to fix it.

    class Solution {
    public:
        string addBinary(string a, string b) {
            
            string ans;
            
            bool carry = false;
            int max = 0;
            int x[a.size()];
            int y[b.size()];
            int res[a.size()];
            
            
            
            if (a.size() > b.size())
                max = a.size();
            
            else if (a.size() < b.size())
                max = b.size();
            
            
            else if (a.size() == b.size())
                max = a.size();
            
            for(int i = 0;i < max+1; i++){
                
              if(a[i] == '1')
                x[i] = 1;
              else
                x[i] = 0;
                
              if(b[i] == '1')
                y[i] = 1;
              else
                y[i] = 0;
            }
            
            for (int j; j < max+1; j++){
                
                if (carry){
                x[j]++;
                carry = false;    
                }
                
                if(x[j]+y[j] == 1)
                res[j] = 1;
                
                else if(x[j]+y[j] == 0)
                res[j] = 0;
                
                else if(x[j]+y[j] > 1){
                res[j] = 0;
                carry = true;
                }
            }    
                switch(res[0]){
                 case 0: ans = '0';
                 break;
                 
                 case 1: ans = '1';
                 break;
                }
                
               for(int k = 1; k < max+1; k++){
                
                switch(res[k]){
                 case 0: ans = '0';
                 break;
                 
                 case 1: ans = '1';
                 break;
                }
               }
               
               return ans;
        }
    };

Log in to reply
 

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