415. Add Strings

来源:互联网 发布:电子烟推荐 知乎2017 编辑:程序博客网 时间:2024/05/16 14:02

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.
public class Solution {    public String addStrings(String num1, String num2) {        String longer = num1;String shorter = num2;if (longer.length() < shorter.length()) {longer = num2;shorter = num1;}int m = longer.length();int n = shorter.length();char l[] = longer.toCharArray();char s[] = shorter.toCharArray();char base = '0';int remainder = 0;int tmp;StringBuilder res = new StringBuilder();for (int i = n - 1; i >= 0; i--) {m--;tmp = l[m] + s[i] - 2 * base + remainder;remainder = tmp / 10;res.append(tmp % 10);}for (int i = m - 1; i >= 0; i--) {tmp = l[i] - base + remainder;remainder = tmp / 10;res.append(tmp % 10);}if (remainder != 0)res.append(remainder);return res.reverse().toString();    }}



0 0
原创粉丝点击