友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

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.

  • 一刷

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * @author D瓜哥 · https://www.diguage.com
 * @since 2024-09-20 22:18:41
 */
public String addStrings(String num1, String num2) {
  int max = 0, diff = 0;
  if (num1.length() < num2.length()) {
    String tmp = num1;
    num1 = num2;
    num2 = tmp;
  }
  max = num1.length();
  diff = max - num2.length();
  int carry = 0;
  String result = "";
  for (int i = max - 1; i >= 0; i--) {
    int n1 = num1.charAt(i) - '0';
    int n2 = 0;
    if (i - diff >= 0) {
      n2 = num2.charAt(i - diff) - '0';
    }
    int sum = n1 + n2 + carry;
    carry = sum / 10;
    result = (sum % 10) + result;
  }
  return carry == 0 ? result : "1" + result;
}