zoukankan      html  css  js  c++  java
  • [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 }
  • 相关阅读:
    js捕获activex事件
    any cpu ×86 ×64
    android手机设备查看/data/data
    this android sdk requires android developer toolkit version
    oracle函数获取汉字拼音的首字母
    Go语言最佳实践——异常和错误
    Go语言最佳实践——通道和并发
    Go语言最佳实践——面向对象
    对闭包的理解
    Go 的垃圾回收机制在实践中有哪些需要注意的地方(转)
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10708512.html
Copyright © 2011-2022 走看看