1218-2019-LEETCODE-415-字符串相加

进位问题没处理好,不能直接写成add += (n1 + n2) % 10;要写成add += (add + (n1 + n2) % 10);
进位问题保证,每一位的进位 = (之前的进位 + 当前两位数字的和)/ 10;
而且自己多写了很多语句。

public String addStrings(String num1, String num2) {
        int len1 = num1.length();
        int len2 = num2.length();
        StringBuilder stringBuilder = new StringBuilder("");
        int n1 = 0;
        int n2 = 0;
        int add = 0;
        int res = 0;
        for (int i = len1 - 1,j = len2 - 1; i >= 0 || j >= 0 ; i--,j--) {
            res = add;
            if (i >= 0){
                n1 = num1.charAt(i) - '0';
            }else {
                n1 = 0;
            }
            if (j >= 0){
                n2 = num2.charAt(j) - '0';
            }else {
                n2 = 0;
            }
            //修改add += (n1 + n2)/10; 为 add = (add + (n1 + n2))/ 10;
            add = (add + (n1 + n2))/ 10;
            res = (res + (n1 + n2)) % 10;
            stringBuilder.insert(0,res);
        }
        if (add != 0){
            stringBuilder.insert(0,add);
        }
        return stringBuilder.toString();
    }

优化版来源:
https://leetcode-cn.com/problems/add-strings/solution/add-strings-shuang-zhi-zhen-fa-by-jyd/

public String addStrings(String num1, String num2) {
        StringBuilder res = new StringBuilder("");
        int i = num1.length() - 1, j = num2.length() - 1, carry = 0;
        while(i >= 0 || j >= 0){
            int n1 = i >= 0 ? num1.charAt(i) - '0' : 0;
            int n2 = j >= 0 ? num2.charAt(j) - '0' : 0;
            int tmp = n1 + n2 + carry;
            carry = tmp / 10;
            res.append(tmp % 10);
            i--; j--;
        }
        if(carry == 1) res.append(1);
        return res.reverse().toString();
    }
发布了98 篇原创文章 · 获赞 0 · 访问量 2217

猜你喜欢

转载自blog.csdn.net/weixin_43221993/article/details/103642670