Big Integer Addition

来源:互联网 发布:如何注册淘宝商标 编辑:程序博客网 时间:2024/06/15 19:16

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

 注意事项
  • 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.
样例

Given num1 = "123", num2 = "45"
return "168"


public String addStrings(String num1, String num2) {        int len1 = num1.length() - 1, len2 = num2.length() - 1;        String result = "";        int pre = 0;        while (len1 >= 0 && len2 >= 0) {            int a = num1.charAt(len1) - '0';            int b = num2.charAt(len2) - '0';            int temp = a + b + pre;            result += temp % 10;            pre = temp / 10;            len1--;            len2--;        }        if (len1 != -1) {            for (int k = len1; k >= 0; k--) {                int a = num1.charAt(k) - '0';                int temp = a + pre;                result += temp % 10;                pre = temp / 10;            }        } else {            for (int k = len2; k >= 0; k--) {                int a = num2.charAt(k) - '0';                int temp = a + pre;                result += temp % 10;                pre = temp / 10;            }        }        if (pre != 0) {            result += pre;        }        return new StringBuilder(result).reverse().toString();    }