LeetCode 415. 字符串相加

题目描述

🔥 415. 字符串相加

image-20230304213815480

思路分析

加法问题

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func addStrings(num1 string, num2 string) string {
	p1, p2 := len(num1)-1, len(num2)-1
	carry := 0
	res := ""
	for p1 >= 0 || p2 >= 0 || carry > 0 {
		sum := carry
		if p1 >= 0 {
			sum += int(num1[p1] - '0')
			p1--
		}
		if p2 >= 0 {
			sum += int(num2[p2] - '0')
			p2--
		}
		res = strconv.Itoa(sum%10) + res
		carry = sum / 10
	}
	return res
}

🍏 点击查看 Java 题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
    public String addStrings(String num1, String num2) {
        StringBuilder res = new StringBuilder();
        int p1 = num1.length() - 1;
        int p2 = num2.length() - 1;
        int carry = 0;
        while (p1 >= 0 || p2 >= 0 || carry > 0) {
            int total = carry;
            if (p1 >= 0) {
                total += num1.charAt(p1) - '0';
                p1--;
            }
            if (p2 >= 0) {
                total += num2.charAt(p2) - '0';
                p2--;
            }
            carry = total / 10;
            res.insert(0, total % 10);
        }
        return res.toString();
    }
}
本文作者:
本文链接: https://hgnulb.github.io/blog/2022/09159489
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!