Problem
Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
Solution: Brute Force
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Author: Huahua // Running time: 13 ms class Solution { public: string addStrings(string num1, string num2) { if (num1.length() < num2.length()) swap(num1, num2); num1 = "0" + num1; int l1 = num1.length(); int l2 = num2.length(); for (int i = 0; i < l1 - 1; ++i) { if (i < l2) num1[l1 - i - 1] += (num2[l2 - i - 1] - '0'); if (num1[l1 - i - 1] > '9') { num1[l1 - i - 1] -= 10; ++num1[l1 - i - 2]; } } return (num1[0] != '0') ? num1 : num1.substr(1); } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment