My 4 ms question. Anything faster?


  • 0
    C
    class Solution {
    public:
    
        string addBinary(string a, string b) {
            //have to know which one has larger size
            string big, small, result;
            if(a.length() >= b.length())
            {
                big = a; // a always bigger even if the same
                small = b;
            }
            else
            {
                big = b;
                small =  a;
            }
            
      //pad the one that has shorter string with 0
            if(big.length() > small.length())
            {
                int diff = (big.length() - small.length());
                for(int i = 0; i < diff; i++)
                {
            
                    small = '0' + small;
                    
                    
                }
            }
            
            // change to integer and add them together
            int carry = 0;
            for(int i = (big.length() - 1); i >= 0; i--)
            {        
                // find the carry and remainder
                // change back to string
                int resultint = 0;
                int bigint = big[i] - '0';
                int smallint = small[i] - '0';
                resultint =  bigint + smallint + carry;
                //divide for msb // rem for lsb
                int rem = resultint % 2;
                carry = resultint/2;
                char rem_str = rem + '0';
                result = rem_str + result;
            }
    
            if(carry)
            {
                return ('1' + result);
            }
            else
            return result;
        }
    };

  • 0

    Yes, looks like almost every C solution is faster.


Log in to reply
 

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