Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
- The length of both
num1andnum2is < 5100. - Both
num1andnum2contains only digits0-9. - Both
num1andnum2does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
這道題讓我們求兩個字符串的相加,之前 LeetCode 出過幾道類似的題目,比如二進制數相加,還有鏈表相加,或是字符串加1,基本思路很類似,都是一位一位相加,然后算和算進位,最后根據進位情況看需不需要補一個高位,難度不大,參見代碼如下:
class Solution { public: string addStrings(string num1, string num2) { string res = ""; int m = num1.size(), n = num2.size(), i = m - 1, j = n - 1, carry = 0; while (i >= 0 || j >= 0) { int a = i >= 0 ? num1[i--] - '0' : 0; int b = j >= 0 ? num2[j--] - '0' : 0; int sum = a + b + carry; res.insert(res.begin(), sum % 10 + '0'); carry = sum / 10; } return carry ? "1" + res : res; } };
討論:由熱心網友 zzcRq1 提供了一種 Follow up,當字符串中有小數點和負號怎么處理。博主稍微想了一下,感覺還挺麻煩的,首先應該判斷有幾個負號,若只有一個,則是減法,而若負號的個數是0個或者是2個的時候,則還是加法。而小數點的處理就是將小數部分和整數部分拆分出來,分別進行加法和減法,最后再拼接上去,感覺大概應該是這樣處理的,感興趣的童鞋可以寫個代碼實現一樣,可以在評論區貼上你的代碼哈~
Github 同步地址:
https://github.com/grandyang/leetcode/issues/415
類似題目:
Add to Array-Form of Integer
參考資料:
https://leetcode.com/problems/add-strings/
https://leetcode.com/problems/add-strings/discuss/90453/C%2B%2B_Accepted_13ms
https://leetcode.com/problems/add-strings/discuss/90436/Straightforward-Java-8-main-lines-25ms
