Leetcode: Multiply Strings

來源:互聯網
上載者:User

標籤:style   blog   color   os   io   ar   for   div   代碼   

Given two numbers represented as strings, return multiplication of the numbers as a string.Note: The numbers can be arbitrarily large and are non-negative.

大整數的字串乘法,我本來對字串表示的大整數就不是太熟悉,至於溢出該怎麼處理也是不大清楚,所以參考了別人的做法,然後自己憑著印象重做了一次

    • 直接乘會溢出,所以每次都要兩個single digit相乘,最大81,不會溢出。
    • 比如385 * 97, 就是個位=5 * 7,十位=8 * 7 + 5 * 9 ,百位=3 * 7 + 8 * 9 …
      可以每一位用一個Int表示,存在一個int[]裡面。
    • 這個數組最大長度是num1.len + num2.len,比如99 * 99,最大不會超過10000,所以4位就夠了。
    • 這種個位在後面的,不好做(10的0次方,可惜對應位的數組index不是0而是n-1),
      所以乾脆先把string reverse了代碼就清晰好多。
    • 最後結果前面的0要清掉。

這裡面的方法比較巧妙,也比較典型,需要掌握。還有需要注意溢出處理,這裡的處理是:如果最高位產生進位carry,那麼直接忽略這個carry

 1 public class Solution { 2     public String multiply(String num1, String num2) { 3         num1 = new StringBuffer(num1).reverse().toString(); 4         num2 = new StringBuffer(num2).reverse().toString(); 5         int[] n1 = new int[num1.length()]; 6         int[] n2 = new int[num2.length()]; 7         int[] temp = new int[num1.length() + num2.length()]; 8         for (int i = 0; i < num1.length(); i++) { 9             n1[i] = (int)(num1.charAt(i) - ‘0‘); 10             for (int j = 0; j < num2.length(); j++) {11                 n2[j] = (int)(num2.charAt(j) - ‘0‘);12                 temp[i + j] += n1[i] * n2[j]; 13             }14         }15         16         StringBuffer sb = new StringBuffer();17         int digit = 0;18         int carry = 0;19         for (int k = 0; k < temp.length; k++) {20             digit = temp[k] % 10;21             carry = temp[k] / 10;22             sb.insert(0, digit);23             if (k < temp.length - 1) {24                 temp[k + 1] += carry;25             }26         }27         28         while (sb.length() > 0 && sb.charAt(0) == ‘0‘) {29             sb.deleteCharAt(0);30         }31         return sb.length() == 0? "0" : sb.toString();32     }33 }

 

Leetcode: Multiply Strings

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.