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
          主站蜘蛛池模板: 凌源市| 石嘴山市| 唐海县| 新乡县| 吉林省| 大同市| 西峡县| 平安县| 太保市| 庆元县| 来宾市| 新疆| 东莞市| 白水县| 平谷区| 宝坻区| 塔城市| 霍城县| 腾冲县| 潢川县| 汉寿县| 渝北区| 孝感市| 汪清县| 北川| 白水县| 平湖市| 太仓市| 易门县| 五大连池市| 五华县| 辽宁省| 东安县| 平凉市| 开平市| 昌都县| 武强县| 建始县| 宕昌县| 庆阳市| 陆良县|