415. Add Strings

Easy

Given two non-negative integers 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.
package leetcode.easy;

public class AddStrings {
public String addStrings(String num1, String num2) {
final int m = num1.length();
final int n = num2.length();
int p1 = m - 1, p2 = n - 1;
int carry = 0;
StringBuilder sb = new StringBuilder();
while (p1 >= 0 || p2 >= 0 || carry > 0) {
int sum = carry + (p1 >= 0 ? num1.charAt(p1) - '0' : 0) + (p2 >= 0 ? num2.charAt(p2) - '0' : 0);
carry = sum / 10;
sb.append((char) (sum % 10 + '0'));
p1--;
p2--;
}
return sb.reverse().toString();
} @org.junit.Test
public void test() {
System.out.println(addStrings("0", "0"));
}
}
05-24 11:06