ARTS第一周 2019-04-28

Algorithm:每周至少做一個 leetcode 的算法題

  1. Add Strings
    Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. 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的人可以看的懂,強推啊。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容