Add Strings Leetcode

时间:2023-03-08 16:31:59

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.

这道题不能用long会越界,所以只能用string直接来append。精髓在于设置一个变量来储存进位。

自己先写了一个用boolean型flag来储存进位,结果代码逻辑麻烦极了。。。要考虑到两个数字相加等于9,再加上进位的1等于10的情况,还要考虑到两个数相加,和的长度长于任何一个数的长度的时候,最高位也要加上1。

这是我一开始写的代码,自己都看不下去了。。。

public class Solution {
public String addStrings(String num1, String num2) {
if (num1 == null || num2 == null) {
return null;
}
int sum = 0;
StringBuilder str = new StringBuilder();
for (int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0; i--, j--) {
int x = i < 0 ? 0 : num1.charAt(i) - '0';
int y = j < 0 ? 0 : num2.charAt(j) - '0';
sum = x + y; sum = sum % 10;
if (flag) {
if (sum + 1 >= 10) {
flag = true;
str.append((sum + 1) % 10);
} else {
str.append(sum + 1);
flag = false;
}
} else {
str.append(sum);
}
if (x + y >= 10) {
flag = true;
} }
if (flag) {
str.append(1);
}
return str.reverse().toString();
}
}

但其实有更简洁的办法,用一个int型代表最高位,当它是1的时候继续循环append。

public class Solution {
public String addStrings(String num1, String num2) {
if (num1 == null || num2 == null) {
return null;
}
int carry = 0;
StringBuilder str = new StringBuilder();
for (int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0 || carry == 1; i--, j--) {
int x = i < 0 ? 0 : num1.charAt(i) - '0';
int y = j < 0 ? 0 : num2.charAt(j) - '0';
str.append((x + y + carry) % 10);
carry = (x + y + carry) / 10;
}
return str.reverse().toString();
}
}

逻辑清晰多了。。。= =