改进前的代码:
public class leetcode415 {
private StringBuilder res = new StringBuilder();
public String addStrings(String num1, String num2) {
int length1 = num1.length();
int length2 = num2.length();
int count = 1;
boolean isAddOne = false;
while (length1 - count >=0 && length2 - count >= 0) {
int temp = num1.charAt(length1-count) - '0' + num2.charAt(length2-count)-'0';
if (isAddOne) {
temp++;
}
if (temp < 10) {
res.append(temp);
isAddOne = false;
} else {
res.append(temp%10);
isAddOne = true;
}
count++;
}
if (length1 == length2 && isAddOne) {
res.append(1);
} else if (length1 > length2) {
processMul(num1,length1,count,isAddOne);
} else {
processMul(num2,length2,count,isAddOne);
}
return res.reverse().toString();
}
private void processMul(String s, int length,int count,boolean isAddOne) {
while (length - count >=0) {
int temp = s.charAt(length-count) - '0';
if (isAddOne) {
temp++;
}
if (temp < 10) {
res.append(temp);
isAddOne = false;
} else {
res.append(temp%10);
isAddOne = true;
}
count++;
}
if (isAddOne) {
res.append(1);
}
}
}
改进点:
1.较短的那个字符串可以在前面补0,不用重新执行那个循环!
第一次改进后:
public class leetcode415 {
public String addStrings(String num1, String num2) {
int length1 = num1.length();
int length2 = num2.length();
int count = 1;
StringBuilder res = new StringBuilder();
boolean isAddOne = false;
while (length1 - count >=0 || length2 - count >= 0) {
int number1 = length1 - count >= 0?num1.charAt(length1 - count)-'0':0;
int number2 = length2 - count >= 0?num2.charAt(length2 - count)-'0':0;
int temp = number1 + number2;
if (isAddOne) {
temp++;
}
if (temp < 10) {
res.append(temp);
isAddOne = false;
} else {
res.append(temp%10);
isAddOne = true;
}
count++;
}
if (isAddOne) {
res.append(1);
}
return res.reverse().toString();
}
}
改进点:
1.length1 - count 和 length2 - count 没必要,可以直接用两个变量来代替。
2.不用区分temp是否小于10,res.append(temp%10)都成立。
3.isAddOne 的赋值可以用三元运算符。
第二次改进后:
public class leetcode415 {
public String addStrings(String num1, String num2) {
int p1 = num1.length() - 1;
int p2 = num2.length() - 1;
StringBuilder res = new StringBuilder();
boolean isAddOne = false;
while (p1 >=0 || p2 >= 0) {
int number1 = p1 >= 0?num1.charAt(p1)-'0':0;
int number2 = p2 >= 0?num2.charAt(p2)-'0':0;
int temp = number1 + number2;
if (isAddOne) {
temp++;
}
res.append(temp%10);
isAddOne = temp>=10;
p1--;
p2--;
}
if (isAddOne) {
res.append(1);
}
return res.reverse().toString();
}
}