415. Add Strings

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.

class Solution {
    public String addStrings(String num1, String num2) {
        int l1 = num1.length();
        int l2 = num2.length();
        int carry = 0;
        int c1 = l1-1, c2 = l2-1;
        StringBuilder res = new StringBuilder();
        while(c1 >= 0 || c2 >= 0){
            int cur1 = c1 >= 0 ? (num1.charAt(c1) - '0') : 0;
            int cur2 = c2 >= 0 ? (num2.charAt(c2) - '0') : 0;
            int sum = cur1 + cur2 + carry;
            int digit = sum % 10;
            carry = sum / 10;
            res.insert(0, digit);
            if(c1 >= 0) c1--;
            if(c2 >= 0) c2--;
        } 
        if(carry == 1){
            res.insert(0, 1);
            System.out.println(carry);
        }
            
        return res.toString();
    }
}

 

 

和add two numbers差不多

posted @ 2020-06-06 10:29  Schwifty  阅读(196)  评论(0编辑  收藏  举报