415. Add Strings

  • 41.3%

https://leetcode.com/problems/add-strings/

Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

java

25ms, October 17, 2016

https://discuss.leetcode.com/topic/62310/straight-forward-java-10-main-lines-25ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Solution {
public String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder();
int carry = 0;
for(int i=num1.length()-1, j=num2.length()-1; i>=0 || j>=0; i--, j--){
int x = i < 0 ? 0 : num1.charAt(i) - '0';
int y = j < 0 ? 0 : num2.charAt(j) - '0';
sb.append((x+y+carry)%10);
carry = (x+y+carry) / 10;
}

if(carry != 0)
sb.append(carry);
return sb.reverse().toString();
}
}

cpp

16ms, October 17, 2016

https://discuss.leetcode.com/topic/62305/c-_accepted_13ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
string addStrings(string num1, string num2) {
int n1 = num1.size(), i = n1 - 1;
int n2 = num2.size(), j = n2 - 1;
int carry = 0;
string res = "";
while(i>=0 || j>= 0 || carry){
long sum = 0;
if(i >= 0){
sum += (num1[i] - '0');
i--;
}
if(j >= 0){
sum += (num2[j] - '0');
j--;
}
sum += carry;
carry = sum / 10;
sum = sum % 10;
res = to_string(sum) + res;
}
return res;
}
};
谢谢你,可爱的朋友。