LeetCode43_Multiply Strings
来源:互联网 发布:php foreach 编辑:程序博客网 时间:2024/06/05 09:48
Multiply Strings
问题描述
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
**Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
**
中文简介
这道题就是把两个字符串代表的整数进行乘法运算,可以说是大数乘法(因为int或者long能代表的数还是有限的),之前写过一个,采用模拟乘法计算的竖式的形式。这次从网上发现了另外一种算法。
对于乘法计算,可以根据规律得到相应的算法。分别计算结果的每一位,把这些单独的位连接起来就是最后的计算结果了。那么怎么计算每一位呢。
比如1234*12
第一位就是4*2
第二位就是4*1+3*2
第三位就是3*1+2*2
第四位就是2*1+1*2
第五位就是1*1+0*2
可以看出关系是相关位附近的数对应积之和
根绝以上信可以写出具体的代码
public class Solution43 { public static void main(String[] args) { Solution43 solution43 = new Solution43(); System.out.println("args = [" + solution43.multiply("1111","222222") + "]"); } public String multiply(String num1, String num2) { if(num1==null||num2==null){ return null; } if(num1.charAt(0)=='0'||num2.charAt(0)=='0'){ return "0"; } StringBuilder stringBuilder= new StringBuilder(); int num = 0; for(int i = num1.length()+num2.length()-1;i>=0;i--){ //对应位附近的数字范围 for(int j = Math.min(num1.length(),i)-1;j>=0;j--){ //如果超过了范围,跳过 if(i-j<=num2.length()){ num+=(num1.charAt(j)-'0')*(num2.charAt(i-j-1)-'0'); } } if(i!=0 || num>0) stringBuilder.append(num%10); num = num/10; } //需要转换String的顺序。 return stringBuilder.reverse().toString(); }}
LeetCode学习笔记Gtihub,持续更新
https://github.com/yanqinghe/leetcode
阅读全文
0 0
- LeetCode43_Multiply Strings
- ★leetcode43_Multiply Strings
- Strings
- Strings
- strings
- Strings
- Strings
- Strings
- strings
- Strings
- Foundation - strings
- Localizable.strings
- C++ Strings
- strings.cpp
- strings.h
- C++ Strings
- Splitting strings
- Casting Strings
- LeetCode日常刷题(2)
- 【死磕Java并发】-----J.U.C之阻塞队列:LinkedTransferQueue
- C++ error C2662: “LinkNode<T> *List<T>::Locate(int)”: 不能将“this”指针从“const List<int>”转换为“List<int> &”
- 巧妙设计一个mobile or pc 的登录界面
- 怎么将cocos2d-js 3.x 成功在android平台编译打包 (测试ok)
- LeetCode43_Multiply Strings
- 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛M题
- Linux系统该怎么学?运维老鸟的经验心得。
- 链表的带参数排序,可以通过姓名、成绩进行升序或降序操作
- 未排序正整数数组中累加和为给定值的最长子数组长度
- String 中的==
- 模拟登录正方教务管理系统-JAVA实现
- Hadoop MapReduce 简单案例--求素数个数
- vue 2 使用Bus.js进行兄弟(非父子)组件通信 简单案例