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 閱讀(144) 評論(0)  編輯  收藏 所屬分類: Leetcode
          主站蜘蛛池模板: 大丰市| 中牟县| 彩票| 寻乌县| 南开区| 潍坊市| 铜梁县| 顺平县| 汽车| 长宁区| 宜兴市| 饶平县| 秭归县| 荥阳市| 绥芬河市| 盐源县| 蕲春县| 乳源| 鸡东县| 黄山市| 眉山市| 南郑县| 达州市| 驻马店市| 瑞丽市| 丰顺县| 武川县| 晴隆县| 固镇县| 麻江县| 平陆县| 泰和县| 清新县| 禄劝| 博兴县| 乌鲁木齐市| 普定县| 普格县| 龙里县| 罗平县| 汉川市|