• [leetcode]43. Multiply Strings高精度乘法


    Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

    Example 1:

    Input: num1 = "2", num2 = "3"
    Output: "6"

    Example 2:

    Input: num1 = "123", num2 = "456"
    Output: "56088"

    Note:

    1. The length of both num1 and num2 is < 110.
    2. Both num1 and num2 contain only digits 0-9.
    3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.
    4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

    题意:

    高精度乘法。

    Solution1: Math 

    Do the simulation like how computer will do multiplication operation

    1一个char对应1个digit, 

    digit相乘后,注意其乘积结果可能需要进位

    code

     1 /*
     2 Time: O(n^2). We use nested 2 for loop
     3 Space: O(n). We use int[] to save intermedia infor
     4 */
     5 
     6 class Solution {
     7     public String multiply(String num1, String num2) {
     8         if(num1.length()==0 || num2.length()==0) return "0";
     9         int len1 = num1.length();
    10         int len2 = num2.length();
    11         int [] result = new int [len1+len2];
    12         
    13         for(int i = len1-1; i>=0; i--){
    14             for(int j = len2-1; j>=0;j--){
    15                 int mul = (num1.charAt(i)-'0')*(num2.charAt(j)-'0');
    16                 int idx = i+j+1;
    17                 // 可能会进位
    18                 int carryIdx = i+j;
    19                 mul = mul + result[idx];
    20                 result[idx] = mul % 10;
    21                 result[carryIdx] = result[carryIdx] + mul/10;
    22             }
    23         }
    24         StringBuilder sb = new StringBuilder();
    25         for(int res: result){
    26             if(sb.length()!=0 || res!=0) sb.append(res);
    27         } 
    28         return (sb.length() == 0)? "0" : sb.toString();     
    29     }
    30 }
  • 相关阅读:
    layui 3种导航栏
    SQL语句内做除法得出百分比
    JS 日期比较方法
    JDK 13 的 12 个新特性,真心涨姿势了
    怎么实现单点登录?面试必问!
    厉害了,Apache架构师们遵循的 30 条设计原则
    面试官问线程安全的List,看完再也不怕了!
    Java 类在 Tomcat 中是如何加载的?
    Redis 21问,你接得住不?
    String hashCode 这个数字,很多人不知道!
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10708512.html
Copyright © 2020-2023  润新知