Algorithm:每周至少做一個 leetcode 的算法題
- Add Strings
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
- The length of both num1 and num2 is < 5100.
- Both num1 and num2 contains only digits 0-9.
- Both num1 and num2 does not contain any leading zero.
- You must not use any built-in BigInteger library or convert the inputs to integer directly.
最開始的解法,一定要注意邊界條件:
class Solution {
public String addStrings(String num1, String num2) {
String res = "";
int m = num1.length(), n = num2.length(), i = m - 1, j = n - 1, flag = 0;
while(i >= 0 || j >= 0){
int a, b;
if(i >= 0){
a = num1.charAt(i--) - '0';
}
else{
a = 0;
}
if(j >= 0){
b = num2.charAt(j--) - '0';
}
else{
b = 0;
}
int sum = a + b + flag;
res =(char)(sum % 10 + '0') + res;
flag = sum / 10;
}
return flag == 1 ? "1" + res: res;
}
}
然后看了leetcode上面的討論,發(fā)現(xiàn)大神的解法,代碼清晰,邏輯也很清楚:
class Solution {
public String addStrings(String num1, String num2) {
StringBuilder str = new StringBuilder();
int carry = 0, i = num1.length() - 1, j = num2.length() - 1;
while (carry == 1 || i >= 0 || j >= 0) {
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();
}
}
Review:閱讀并點評至少一篇英文技術(shù)文章
How ClassLoader Works in Java
Class Loaders in Java
總結(jié):這兩篇blog講述了Java當中 java.lang.ClassLoader 的具體工作方式。講述了如何查找class以及裝載class的過程。
Tip:學習至少一個技術(shù)技巧
如何將兩個git repo合并到一個repo,并且不損失任何一個repo的提交歷史? 下面這個blog提供的方法比較好用。
Merging Two Git Repositories Into One Repository Without Losing File History
Share:分享一篇有觀點和思考的技術(shù)文章
學習攻略 | 如何才能學好并發(fā)編程?
極客時間上面的《Java并發(fā)編程實戰(zhàn)》第一篇,寫的非常好。從源頭和綱領(lǐng)上面把握并發(fā),后面的章節(jié)也得很好,從最簡單的開始講起,具有入門基礎(chǔ)java的人可以看的懂,強推啊。