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上面的讨论,发现大神的解法,代码清晰,逻辑也很清楚:
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:阅读并点评至少一篇英文技术文章
How ClassLoader Works in Java
Class Loaders in Java
总结:这两篇blog讲述了Java当中 java.lang.ClassLoader 的具体工作方式。讲述了如何查找class以及装载class的过程。
Tip:学习至少一个技术技巧
如何将两个git repo合并到一个repo,并且不损失任何一个repo的提交历史? 下面这个blog提供的方法比较好用。
Merging Two Git Repositories Into One Repository Without Losing File History
Share:分享一篇有观点和思考的技术文章
学习攻略 | 如何才能学好并发编程?
极客时间上面的《Java并发编程实战》第一篇,写的非常好。从源头和纲领上面把握并发,后面的章节也得很好,从最简单的开始讲起,具有入门基础java的人可以看的懂,强推啊。