这里先po我的代码,很明显的复杂且低效。
class Solution {
public static String addStrings(String num1, String num2) {
char forward = '0';
StringBuffer stringBuffer = new StringBuffer();
int len1 = num1.length(), len2 = num2.length();
String strLong = len1 > len2 ? num1 : num2, strShort = len1 <= len2 ? num1 : num2;
int strTag = 1;
while (strTag <= strShort.length()) {
char[] preAndAns = charAdd(strLong.charAt(strLong.length() - strTag), strShort.charAt(strShort.length() - strTag), forward);//得到进位与结果
forward = preAndAns[0];//取出进位并参与下一趟计算
stringBuffer.append(preAndAns[1]);//存储当前位结果
strTag++;//指针更新
}//第一趟 加完较短的那一个序列之后。 第二趟,剩下较长的序列需要与第一趟计算的结果的进位继续相加
while (strTag <= strLong.length()) {
char[] preAndAns = charAdd('0', strLong.charAt(strLong.length() - strTag), forward);
forward = preAndAns[0];//取出进位并参与下一趟计算
stringBuffer.append(preAndAns[1]);//存储当前位结果
strTag++;//指针更新
}
if (forward > '0') stringBuffer.append(forward);
return new String(stringBuffer.reverse());
}
public static char[] charAdd(char nums1, char nums2, char pre) {
char[] preAndAns = new char[2];//[0] = pre [1] = ans
int i = nums1 - '0' + nums2 - '0' + pre - '0';
preAndAns[0] = (char) (i / 10 + '0');
preAndAns[1] = (char) (i % 10 + '0');
// System.out.println("nums1 is : " + nums1 + " nums2 is : " + nums2 + " pre is : " + pre);
// System.out.println("pre is:" + preAndAns[0] + " ans is:" + preAndAns[1]);
return preAndAns;
}
}
-------------------------------------------------------------------------------------------------
这里再放上示例代码
public String addStrings(String num1, String num2) {
int i = num1.length() - 1, j = num2.length() - 1, carry = 0;
StringBuffer ans = new StringBuffer();
while (i >= 0 || j >= 0 || carry != 0) {
int left = (i >= 0) ? (num1.charAt(i--) - '0') : 0;
int right = (j >= 0) ? num2.charAt(j--) - '0' : 0;
int tempResult = left + right + carry;
ans.append(tempResult % 10);
carry = tempResult / 10;
}
return ans.reverse().toString();
}
总结一下:
为何我的代码十分冗长且低效呢?
就是在字符串拼接的时候的长串与短串在处理的时候。
那么示例代码的处理方式就是,补齐长度,填0,很简单的一个操作,这个思想在计算机组成原理中底层的01二进数的计算中经常使用,但是,我忘了,真该死啊!!