IT技術小屋

          秋風秋雨,皆入我心

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            38 隨筆 :: 1 文章 :: 19 評論 :: 0 Trackbacks
          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.

          對每個數字相乘,記錄到一個數組中,然后對這個數字的每個元素進行進位檢查。主要相乘的時候要分別從兩個數字的最后一位開始,還要記錄偏移量。實現如下:
           1 public class MultiplyStrings {
           2     public String multiply(String num1, String num2) {
           3         int length1 = num1.length();
           4         int length2 = num2.length();
           5         int[] m = new int[length1 + length2];
           6         for (int k = length2 - 1, offset2 = 0; k >= 0; k--, offset2++) {
           7             for (int i = length1 - 1, offset1 = 0; i >= 0; i--, offset1++) {
           8                 m[length1 + length2 - 1 - offset1 - offset2] += (num1.charAt(i) - '0') * (num2.charAt(k) - '0');
           9             }
          10         }
          11         int add = 0;
          12         for (int t = length1 + length2 - 1; t >= 0; t--) {
          13             int value = m[t] + add;
          14             add = value / 10;
          15             m[t] = value % 10;
          16         }
          17         StringBuffer sb = new StringBuffer();
          18         int w = 0;
          19         for (; w < length1 + length2; w++) {
          20             if (m[w] != 0) break;
          21         }
          22         for (int e = w; e < length1 + length2; e++) {
          23             sb.append(m[e]);
          24         }
          25         return sb.length() == 0 ? "0" : sb.toString();
          26     }
          27 }

          posted on 2013-12-23 11:59 Meng Lee 閱讀(138) 評論(0)  編輯  收藏 所屬分類: Leetcode
          主站蜘蛛池模板: 安乡县| 方山县| 永善县| 郓城县| 东安县| 乌什县| 元谋县| 太和县| 苍梧县| 尼玛县| 女性| 天台县| 大连市| 江门市| 山阳县| 锡林浩特市| 松潘县| 宁陕县| 区。| 北碚区| 普格县| 鲁甸县| 静宁县| 南川市| 湖口县| 客服| 湘潭县| 沈丘县| 临汾市| 昭觉县| 浦江县| 青海省| 光山县| 抚宁县| 正阳县| 桑日县| 福贡县| 隆德县| 论坛| 正镶白旗| 沂源县|