leetcode做题总结,题目Multiply Strings 43
2014-12-28 04:23
344 查看
题目是Multiply
Strings
这道题大整数的乘法,和加法一样,需要按位计算然后加起来即可。但是有一个问题要注意的是这里的乘法积很可能非常大,因此需要用数组来储存。在计算的时候数组元素可以大于9,之后再历遍进位即可。
Update 2015/08/31:下面是九章的解法,都差不多
Strings
这道题大整数的乘法,和加法一样,需要按位计算然后加起来即可。但是有一个问题要注意的是这里的乘法积很可能非常大,因此需要用数组来储存。在计算的时候数组元素可以大于9,之后再历遍进位即可。
public class Solution { public String multiply(String num1, String num2) { if(num1==null||num2==null) return ""; if(num1.length()==1&&Integer.parseInt(num1)==0||num2.length()==1&&Integer.parseInt(num2)==0) return "0"; //using StringBuilder in building String String n1 = new StringBuilder(num1).reverse().toString(); String n2 = new StringBuilder(num2).reverse().toString(); int[] sa = new int[n1.length()+n2.length()]; for(int i=0;i<n1.length();i++){ for(int j=0;j<n2.length();j++){ //switching char to int. Cannot us (int)'a'. Another way is Integer.parseInt('a'+""); sa[i+j]+=(n1.charAt(i)-'0')*(n2.charAt(j)-'0'); } } for(int i=0;i<sa.length-1;i++){ sa[i+1]+= sa[i]/10; sa[i]=sa[i]%10; } boolean flag=false; StringBuilder res = new StringBuilder(); for(int i=sa.length-1;i>=0;i--){ if(flag==false&&sa[i]!=0) flag=true; if(flag){ res.append(sa[i]); } } return res.toString(); } }
Update 2015/08/31:下面是九章的解法,都差不多
public class Solution { public String multiply(String num1, String num2) { if (num1 == null || num2 == null) { return null; } int len1 = num1.length(), len2 = num2.length(); int len3 = len1 + len2; int i, j, product, carry; int[] num3 = new int[len3]; for (i = len1 - 1; i >= 0; i--) { carry = 0; for (j = len2 - 1; j >= 0; j--) { product = carry + num3[i + j + 1] + Character.getNumericValue(num1.charAt(i)) * Character.getNumericValue(num2.charAt(j)); num3[i + j + 1] = product % 10; carry = product / 10; } num3[i + j + 1] = carry; } StringBuilder sb = new StringBuilder(); i = 0; while (i < len3 - 1 && num3[i] == 0) { i++; } while (i < len3) { sb.append(num3[i++]); } return sb.toString(); } }
相关文章推荐
- leetcode做题总结,题目Swap Nodes in Pairs 2012/02/14
- leetcode做题总结,题目Binary Tree Inorder Traversal 2012/08/27
- leetcode做题总结,题目Add Two Numbers /Add Binary 2011/11/01&2012/04/02
- leetcode做题总结,题目Search in Rotated Sorted Array I/II 2012/03/02-12/04/09
- leetcode做题总结,题目Search a 2D MatrixI/II 2012/04/06
- LeetCode Online Judge 题目C# 练习 - Multiply Strings
- leetcode做题总结,题目Best Time to Buy and Sell Stock 2012/10/30
- leetcode做题总结,题目First Missing Positive 2012/03/08
- leetcode做题总结,题目Insertion Sort List 2013/11/12
- leetcode做题总结,题目Search Insert Position 2012/03/03
- leetcode做题总结,题目Set Matrix Zeroes 2012/04/06
- leetcode做题总结,题目Validate Binary Search Tree 2012/08/31
- leetcode做题总结,题目Merge k Sorted Lists 2012/02/13
- leetcode做题总结,题目Spiral Matrix I/II 2012/03/24
- leetcode做题总结,题目Merge Sorted Array 2012/05/20
- leetcode做题总结,题目Merge Two Sorted Lists 2012/03/30
- leetcode做题总结,题目Rotate List 2012/03/27
- leetcode做题总结,题目Pow(x, n)-------- 2012/03/19
- leetcode做题总结,题目Search for a Range 2012/03/02
- leetcode做题总结,题目Copy List with Random Pointer 2013/10/03