C# Solution


  • 0
    M
    public string AddStrings(string num1, string num2) {                
        int carryOver = 0;
        string small, large;     
        StringBuilder result = new StringBuilder();         
        
        if (num1.Length < num2.Length)
        {
            small = num1; 
            large = num2; 
        }
        else 
        {
            small = num2; 
            large = num1; 
        }
        
        for (int i = small.Length - 1; i >= 0; i--)
        {
            int op1 = small[i] - '0';
            int op2 = large[i + large.Length - small.Length] - '0';
            int localSum = op1 + op2 + carryOver;             
            
            if (localSum < 10)
            {
                result.Insert(0, localSum.ToString()); 
                carryOver = 0; 
            }
            else 
            {
                result.Insert(0, (localSum - 10).ToString());
                carryOver = 1; 
            }                  
        }
        
        for (int i = large.Length - small.Length - 1; i >= 0; i--)
        {
            int op1 = carryOver; 
            int op2 = large[i] - '0';
            int localSum = op1 + op2;             
            
            if (localSum < 10)
            {
                result.Insert(0, localSum.ToString()); 
                carryOver = 0; 
            }
            else 
            {
                result.Insert(0, (localSum - 10).ToString());
                carryOver = 1; 
            }                                          
        }        
        
        if (carryOver == 1)
        {
            result.Insert(0, "1");            
        }
        
        return result.ToString(); 
    }

Log in to reply
 

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