C# - reverse string after building result


  • 0
    public string AddStrings(string num1, string num2) {
        int i = 0;
        StringBuilder res = new StringBuilder();
        int carry = 0;
        while (i < num1.Length || i < num2.Length || carry > 0)
        {
            int a = i < num1.Length ? num1[num1.Length - 1 - i] - '0' : 0;
            int b = i < num2.Length ? num2[num2.Length - 1 - i] - '0' : 0;
            
            int next = (a + b + carry) % 10;
            carry = (a + b + carry) / 10;
            res.Append(next.ToString());
            i++;
        }
        
        return ReverseString(res.ToString());
    }
    
    public static string ReverseString(string s)
    {
    	char[] arr = s.ToCharArray();
    	Array.Reverse(arr);
    	return new string(arr);
    }

Log in to reply
 

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