leetcode 415. Add Strings
string addStrings(string num1, string num2) { bool carry = false; int len1 = num1.size(); int len2 = num2.size(); int max_len = len1 >= len2 ? len1 : len2; int min_len = len1 < len2 ? len1 : len2; string& max_str = len1 >= len2 ? num1 : num2; string& min_str = len1 < len2 ? num1 : num2; min_len--; max_len--; for (; max_len >= 0; min_len--, max_len--) { int temp = min_len >= 0 ? min_str[min_len] : '0'; int ta = max_str[max_len] - '0' + temp - '0' + carry; if (ta > 9) { carry = true; max_str[max_len] = ta - 10 + '0'; } else { carry = false; max_str[max_len] = ta + '0'; } } if (carry) return "1" + max_str; return max_str; }
【本文章出自博客园willaty,转载请注明作者出处,误差欢迎指出~】