zoukankan      html  css  js  c++  java
  • Multiply Strings大整数乘法

    [抄题]:

    以字符串的形式给定两个非负整数 num1 和 num2,返回 num1 和 num2 的乘积。

     [暴力解法]:

    时间分析:

    空间分析:

    [思维问题]:

     还要找到结果中第一位不等于0的数再添加,没想到

    [一句话思路]:

    套公式, 没有carry进位了,全都是对ans直接进行操作:

    ans[i + j] += a [i] * b[j] 

    全部相乘之后再统一进位

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. 长度用l1 l2来表示,比较简单。二者合并后的新数组要为0新添加一位,变成num[l1 + l2 + 1]
    2. while循环可以加2个条件,括号里不止有一个东西,从而控制几个条件 while (i >= 1 && ans[i] == 0)
    3. 结果添加的时候,index也可以变,从而不用for就一直往后添加 result += ans[i--]

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    没有变量carry,但是有carry进位的过程:直接对ans[]进行操作

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

    public class Solution {
        /**
         * @param num1: a non-negative integers
         * @param num2: a non-negative integers
         * @return: return product of num1 and num2
         */
        public String multiply(String num1, String num2) {
            //mutiply
            int l1 = num1.length();
            int l2 = num2.length();
            int[] ans = new int[l1 + l2 + 1];//add new
    
            for (int i = 0; i < l1; i++) {
                for (int j = 0; j < l2; j++) {
                    ans[i + j] += (num1.charAt(l1 - 1 - i) - '0') * 
                    (num2.charAt(l2 - 1 - j) - '0');
                }
            }
            //carry process
            for (int i = 0; i < l1 + l2; i++) {
                ans[i + 1] += ans[i] / 10;
                ans[i] = ans[i] % 10;//
            }
            //find first position
            int i = l1 + l2;
            while (i >= 1 && ans[i] == 0) {//
                i--;
            }
            //add to ans
            String result = "";
            while (i >= 0) {
                result += ans[i--]; //i should move
            }
            
            return result;
        }
    }
    View Code
  • 相关阅读:
    t
    bert4keras
    embeding应用-airbnb推荐
    The Neural Autoregressive Distribution Estimator
    3.redis desktop manager--redis 可视化工具安装及使用
    Day06作业(postman接口测试)
    DRF学习day01(web应用模式,api接口,RESTful API规范,序列化,Django Rest_Framework)
    restFul接口设计规范
    Vue学习之荏苒资讯项目(一)
    微信小程序开发四:Promise的使用,解决回调地狱
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8463470.html
Copyright © 2011-2022 走看看