Multiply Strings leetcode java


題目

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.

 

題解

 題意就是給你兩個字符串型的數字,給這兩個數字做乘法。

 如果直接轉換成Integer做乘法就會溢出。

 所以要一步一步來。

 

 下面講解引用自(http://leetcodenotes.wordpress.com/2013/10/20/leetcode-multiply-strings-%E5%A4%A7%E6%95%B4%E6%95%B0%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B9%98%E6%B3%95/comment-page-1/#comment-122),非常精巧的寫法:

 

這個題第二遍做code就寫的挺完美的,高興~~幾個要點:

  • 直接乘會溢出,所以每次都要兩個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要清掉。

  代碼如下:

 1     num1 =  new StringBuilder(num1).reverse().toString();
 2     num2 =  new StringBuilder(num2).reverse().toString();
 3      //  even 99 * 99 is < 10000, so maximaly 4 digits
 4       int[] d =  new  int[num1.length() + num2.length()];
 5      for ( int i = 0; i < num1.length(); i++) {
 6          int a = num1.charAt(i) - '0';
 7          for ( int j = 0; j < num2.length(); j++) {
 8              int b = num2.charAt(j) - '0';
 9             d[i + j] += a * b;
10         }
11     }
12     StringBuilder sb =  new StringBuilder();
13      for ( int i = 0; i < d.length; i++) {
14          int digit = d[i] % 10;
15          int carry = d[i] / 10;
16         sb.insert(0, digit);
17          if (i < d.length - 1)
18             d[i + 1] += carry;
19         }
20      // trim starting zeros
21       while (sb.length() > 0 && sb.charAt(0) == '0') {
22         sb.deleteCharAt(0);
23     }
24      return sb.length() == 0 ? "0" : sb.toString();
25 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM