LeetCode 110 Multiply Strings
来源:互联网 发布:2011选秀动态体测数据 编辑:程序博客网 时间:2024/06/06 08:38
Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
分析:
这属于用字符串来模拟数学运算的题目。
明确几点:
1,两个整数相乘,结果的位数最多为两数位数之和,比如99*99;
2,反向保存数字有助于位数的计算。
public class Solution { public String multiply(String num1, String num2) { //两数反向,String没有reverse()方法,所以借助于StringBuffer num1 = new StringBuffer(num1).reverse().toString(); num2 = new StringBuffer(num2).reverse().toString(); //相乘结果最长是num1.length()+num2.length(), 例如,99*99 int[] res = new int[num1.length()+num2.length()]; for(int i=0; i<num1.length(); i++){ int a = num1.charAt(i)-'0'; for(int j=0; j<num2.length(); j++){ int b = num2.charAt(j)-'0'; res[i+j] = res[i+j] + a*b;//先把结果存在相应位置再考虑进位 } } StringBuffer sb = new StringBuffer(); for(int i=0; i<res.length; i++){ int digit = res[i]%10; int carry = res[i]/10; //从头插入 sb.insert(0,digit); if(i < res.length-1) res[i+1] = res[i+1]+carry; } while(sb.length()>0 && sb.charAt(0)=='0') sb.deleteCharAt(0); return sb.length()==0 ? "0" : sb.toString(); }}
0 0
- LeetCode 110 Multiply Strings
- LeetCode: Multiply Strings
- LeetCode Multiply Strings
- LeetCode: Multiply Strings
- [Leetcode] Multiply Strings
- [LeetCode] Multiply Strings
- [Leetcode] Multiply Strings
- LeetCode 45: Multiply Strings
- [LeetCode]Multiply Strings
- [LeetCode] Multiply Strings
- LeetCode-Multiply Strings
- [leetcode] Multiply Strings
- LeetCode - Multiply Strings
- Leetcode: Multiply Strings
- LeetCode题解:Multiply Strings
- leetcode Multiply Strings
- LeetCode Multiply Strings
- LeetCode | Multiply Strings
- 运动检测(前景检测)之(二)混合高斯模型GMM
- 完美发布带摘要的dedecms幻灯片代码
- Canvas save restore存了什么,恢复了什么
- python中如何kill掉线程
- C# DispatcherTimer:传入自定义参数小技巧
- LeetCode 110 Multiply Strings
- Softmax算法:逻辑回归的扩展
- magento上插入、编辑、删除、查询语法 简便方法
- 什么时候需要动态分配内存?
- Html开发规范
- 介绍 JSON
- android ImageView scaleType属性
- PL/SQL连接不上本地ORACLE
- 【Leetcode】Sum Root to Leaf (Sum)