Java for LeetCode 043 Multiply Strings
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.
解题思路一:
BigInteger!!! JAVA实现如下:
import java.math.BigInteger; public class Solution { static public String multiply(String num1, String num2) { BigInteger bi1=BigInteger.valueOf(0); for(int i=0;i<num1.length();i++){ bi1=bi1.multiply(BigInteger.valueOf(10)); bi1=bi1.add(BigInteger.valueOf(num1.charAt(i)-'0')); } BigInteger bi2=BigInteger.valueOf(0); for(int i=0;i<num2.length();i++){ bi2=bi2.multiply(BigInteger.valueOf(10)); bi2=bi2.add(BigInteger.valueOf(num2.charAt(i)-'0')); } return bi1.multiply(bi2).toString(); } }
360 ms Accepted,值得注意的是系统不会自动导入math包,需要在声明时添加。
解题思路二:使用BigInteger总有种作弊的赶脚,题目的真正意思是让我们用加法模拟乘法的过程,JAVA实现如下:
static public String multiply(String num1, String num2) { StringBuilder result=new StringBuilder(); for(int i=0;i<num1.length()+num2.length();i++) result.append('0'); for (int i = num1.length()-1; i >=0; i--) for (int j = num2.length()-1; j>=0; j--) { int tmp = (result.charAt(i+j+1) - '0') + (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); result.replace(i+j+1, i+j+2, ""+tmp % 10); for(int k=i+j;;k--){ tmp=result.charAt(k)- '0' + tmp / 10; result.replace(k, k+1,""+ tmp%10); if(tmp<10) break; } } for (int i = 0; i <result.length(); i++) if(result.charAt(i)!='0') return result.substring(i, result.length()); return "0"; }