zoukankan      html  css  js  c++  java
  • 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 }

  • 相关阅读:
    关于 Mercury_Lc 说明
    Java 对象和类
    Java int 与 Integer 区别
    Java Number & Math 类
    HTML | CSS | JavaScript 常见错误
    B. Heaters ( Codeforces Round #515 (Div. 3) )
    A. Vova and Train ( Codeforces Round #515 (Div. 3) )
    数据结构实验之排序四:寻找大富翁(SDUT 3401)
    JavaScript 与 Java
    A. The Fair Nut and Elevator (Codeforces Round #526 (Div. 2))
  • 原文地址:https://www.cnblogs.com/springfor/p/3889706.html
Copyright © 2011-2022 走看看