Leetcode: 2. 415. Add Strings
Given two non-negative integers num1
and num2
represented as a string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits 0-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:
class Solution {
public String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder();
int num = 0;
int str = 0;
for(int p_1 = num1.length()-1, p_2 = num2.length()-1; p_1 >= 0 || p_2 >= 0; p_1--, p_2--) {
if(p_1 >= 0 && p_2 >= 0)
str = num1.charAt(p_1) - '0' + num2.charAt(p_2) - '0' + num;
else
str = (p_1 >= 0)?(num1.charAt(p_1) - '0' + num):(num2.charAt(p_2) - '0' + num);
num = str / 10;
str %= 10;
sb.append(str);
}
if (num > 0)
sb.append(num);
return sb.reverse().toString();
}
}
网友评论