转载请以链接形式标明出处: 本文出自:103style的博客
主要是 一个 正数 一个负数的情况。
保证测试用例 输入字符串是正常的正负整数。
正负数的字符串长度 不超过 10^9
.
public class LeetCode {
public static void main(String[] args) {
System.out.println(new LeetCode().addString("-12312", "12312"));
System.out.println(-12312 + 12312);
System.out.println(new LeetCode().addString("-145", "12312"));
System.out.println(-145 + 12312);
System.out.println(new LeetCode().addString("154545", "954545"));
System.out.println(154545 + 954545);
System.out.println(new LeetCode().addString("123", "5689"));
System.out.println(123 + 5689);
System.out.println(new LeetCode().addString("-123", "-5689"));
}
public String addString(String a, String b) {
if ((a.charAt(0) == '-') != (b.charAt(0) == '-')) {
// 一正一负
if (a.charAt(0) == '-') {
return check(a, b);
} else {
return check(b, a);
}
} else if (a.charAt(0) == '-' && b.charAt(0) == '-') {
//都是负数
return "-" + addString(a.substring(1), b.substring(1));
}
//都是正数
char[] arr1 = a.toCharArray();
char[] arr2 = b.toCharArray();
int len = Math.max(arr1.length, arr2.length) + 1;
int[] res = new int[len];
int t = 0;
for (int i = len - 1; i >= 0; i--) {
int indexA = (arr1.length - (len - i));
int indexB = (arr2.length - (len - i));
int numA = indexA < 0 ? 0 : (arr1[indexA] - '0');
int numB = indexB < 0 ? 0 : (arr2[indexB] - '0');
t += numA + numB;
res[i] = t % 10;
t = t / 10;
}
int i = 0;
while (res[i] == 0) i++;
StringBuilder builder = new StringBuilder();
while (i < len) builder.append(res[i++]);
return builder.toString();
}
private String check(String negative, String positive) {
if (negative.length() - 1 > positive.length()) {
return "-" + sub(negative.substring(1), positive);
} else if (negative.length() - 1 < positive.length()) {
return sub(positive, negative.substring(1));
} else {
for (int i = 0; i < positive.length(); i++) {
if (negative.charAt(i + 1) > positive.charAt(i)) {
return "-" + sub(negative.substring(1), positive);
} else if (negative.charAt(i + 1) < positive.charAt(i)) {
return sub(positive, negative.substring(1));
}
}
return "0";
}
}
private String sub(String a, String b) {
//a > b 求 a - b
char[] arrA = a.toCharArray();
char[] arrB = b.toCharArray();
int t = 0;
for (int i = 0; i < arrA.length; i++) {
int index = arrB.length - 1 - i;
int numB = index < 0 ? 0 : (arrB[arrB.length - 1 - i] - '0');
int numA = arrA[arrA.length - 1 - i] - '0';
t = numA - numB - t;
if (t >= 0) {
arrA[arrA.length - 1 - i] = (char) ('0' + t);
t = 0;
} else {
arrA[arrA.length - 1 - i] = (char) ('0' + (10 + t));
t = 1;
}
}
return new String(arrA);
}
}