博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode-43-Multiply Strings
阅读量:6876 次
发布时间:2019-06-26

本文共 1278 字,大约阅读时间需要 4 分钟。

算法描述:

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.

解题思路:1 两个数相乘,得到结果最大长度为两个数位数之和。

        2 num1中的i 位和 num2中的j位相乘,其结果在最终结果中所属位置为 i+j和i+j+1。

                  3 注意细节,例如进位等。

string multiply(string num1, string num2) {        if(num1.size()==0 || num2.size()==0) return "0";        string sum(num1.size()+num2.size(),'0');        for(int i = num1.size()-1; i >=0; i--){            for(int j = num2.size()-1; j>=0; j--){                int temp = (num1[i] -'0') * (num2[j] - '0');                temp += sum[i+j+1] - '0';                sum[i+j+1] = temp%10 + '0';                sum[i+j] += temp/10;                            }        }        int index = sum.find_first_not_of('0');        if(string::npos != index)            return sum.substr(index);        return "0";    }

 

转载于:https://www.cnblogs.com/nobodywang/p/10334338.html

你可能感兴趣的文章
golang实现文字云算法
查看>>
artTemplate 学习网址和书籍
查看>>
C++对象内存分配
查看>>
Cong!
查看>>
PHP语言拓展json模块
查看>>
spring 配置文件applicationContext.xml命名空间及标签解析
查看>>
我的友情链接
查看>>
回到顶部代码(兼容IE6)
查看>>
web.xml文件的作用
查看>>
iOS开发篇——OC延展类目协议介绍
查看>>
桌面客户端
查看>>
exchange online 用户许可证迁移常见问题
查看>>
ELK调优
查看>>
mysql性能优化2
查看>>
【Java】Java 实现导出excel表 POI
查看>>
如何对待用户需求的几点思考
查看>>
POJ 3686 The Windy's 最小费用最大流
查看>>
RH124-13 软件包安装与升级
查看>>
我的友情链接
查看>>
1.python入门到精通
查看>>