[LeetCode] 415. Add Strings 字符串相加
阿新 • • 發佈:2018-03-26
input a + b ring [] end etc insert size not
Given two non-negative numbers 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
兩個只含有數字的字符串相加。
解法: 對於每個字符轉成對應的整數,然後相加,結果在寫入res。
Python:
class Solution(object): def addStrings(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ result = [] i, j, carry = len(num1) - 1, len(num2) - 1, 0 while i >= 0 or j >= 0 or carry: if i >= 0: carry += ord(num1[i]) - ord(‘0‘); i -= 1 if j >= 0: carry += ord(num2[j]) - ord(‘0‘); j -= 1 result.append(str(carry % 10)) carry /= 10 result.reverse() return "".join(result)
C++:
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; } };
[LeetCode] 415. Add Strings 字符串相加