p415

LeetCode p415 Add Strings 题解

1.题目:

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

Note:

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

题意:

输入两个数字的字符串,返回他们相加的和。

2.解题思路:

见代码

3.代码


[title] [] [url] [link text]
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
26
 
public class Solution {
public String addStrings(String num1, String num2) {
StringBuilder sBuilder = new StringBuilder();

int len1 = num1.length() - 1;
int len2 = num2.length() - 1;
int c = 0;
for (; len1 >= 0 || len2 >= 0; len1--, len2--) {

int i = c;
if (len1 >= 0)
i += num1.charAt(len1) - '0';
if (len2 >= 0)
i += num2.charAt(len2) - '0';
c = i / 10;
i = i % 10;
char a = (char) ('0' + i);
sBuilder.append(a);
}

if (c > 0)
sBuilder.append((char) ('0' + c));
return sBuilder.reverse().toString();
}
}

4.一些总结: