• 欢迎光临~

leetcode-415-easy

开发技术 开发技术 2022-10-19 次浏览

Add String
思路一: 模拟加法运算,字符串前面填零

public String addStrings(String num1, String num2) {
    int max = Math.max(num1.length(), num2.length());
    num1 = pad(num1, max);
    num2 = pad(num2, max);

    int p = 0;
    StringBuilder result = new StringBuilder();
    for (int length = num1.length() - 1; length >= 0; length--) {
        int sum = Integer.parseInt(Character.toString(num1.charAt(length))) +
                Integer.parseInt(Character.toString(num2.charAt(length))) + p;
        if (sum >= 10) {
            p = 1;
            result.insert(0, sum % 10);
        } else {
            p = 0;
            result.insert(0, sum);
        }
    }
    if (p == 1) {
        result.insert(0, '1');
    }

    return result.toString();
}

public static String pad(String str, int len) {
    if (str.length() >= len) return str;

    StringBuilder strBuilder = new StringBuilder(str);
    for (int i = 0; i < (len - str.length()); i++) {
        strBuilder.insert(0, '0');
    }
    return strBuilder.toString();
}

思路二: 做法和思路一一样,细节优化:双指针,指针指向字符串尾部,另外 ‘1’-'0' 可以直接算 char 类型 ‘1’ 对应的 int 值

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();
}
程序员灯塔
转载请注明原文链接:leetcode-415-easy
喜欢 (0)