Problem

Given two non-negative integersnum1andnum2represented as string, return the sum ofnum1andnum2.

Note:

  1. The length of bothnum1andnum2is < 5100.
  2. Bothnum1andnum2contains only digits0-9.
  3. Bothnum1andnum2does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integerdirectly.

思路(StringBuilder)

  • first to know which number is the longerst
  • go through each character of the long one and add the corresponding character of short one to it.
  • at the same time record the carry bit for the next iteration.
  • then append to StringBuilder
  • finally append the carry bit if it is larger than 0
  • reverse the StringBuilder
    public String addStrings(String num1, String num2) {

        StringBuilder sb = new StringBuilder();
        String longStr = null;
        String shortStr = null;
        if (num1.length() > num2.length()) {
            longStr = num1;
            shortStr = num2;
        } else {
            longStr = num2;
            shortStr = num1;
        }
        int carry = 0;
        for (int i = 0; i < longStr.length(); i++) {
            int sc = 0;
            if (i < shortStr.length()) {
                sc = shortStr.charAt(shortStr.length() - 1 - i) - '0';
            } 
            int lc = longStr.charAt(longStr.length() - 1 - i) - '0';

            int sum = sc + lc + carry;
            carry = sum / 10;
            sb.append(sum % 10);
        }
        if (carry > 0) sb.append(carry);

        return sb.reverse().toString();
    }

results matching ""

    No results matching ""