Leetcode43 Multiply Strings

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.

Solution1

  • 最简单的方法就是完全模拟乘法的运算规则,下面的代码是用了两个辅助函数,其中help1方法是用来计算第一个数和个位数相乘的,help2是用来对两个字符串代表的数进行求和的。
public class Solution {
    public String multiply(String num1, String num2) {
        if(num1.length()==0||num2.length()==0) return "";
        String result = "", zeros = "";
        for(int i=num2.length()-1;i>=0;i--,zeros += "0"){
            int num = num2.charAt(i) - '0';
            if(num==0) continue;
            else if(num==1) result = help2(result,num1+zeros);
            else result = help2(result,help1(num1,num)+zeros);
        }
        return result==""?"0":result;
    }
    public String help1(String num1, int num){//大数和个位数相乘
        String s = "";
        int ci = 0;
        for(int i=num1.length()-1;i>=0;i--){
            int temp = (num1.charAt(i)-'0')*num + ci;
            s = String.valueOf(temp%10) + s;
            ci = temp/10;
        }
        if(ci!=0) s = String.valueOf(ci) + s;
        return s;
    }
    public String help2(String s1, String s2){//大数相加
        String s = "";
        for(int i=s1.length()-1,j=s2.length()-1,ci=0;i>=0||j>=0||ci>0;){
            int temp = (i>=0?s1.charAt(i--)-'0':0) + (j>=0?s2.charAt(j--)-'0':0) + ci;
            s = String.valueOf(temp%10) + s;
            ci = temp/10;
        }
        return s;       
    }
}

Solution2

  • 上面的方法虽然能解,但是过于繁琐,并且容易出错。下面给出一种更优化的方法。对照着数仔细体会其中的过程。
public class Solution {
    public String multiply(String num1, String num2) {
        int n1 = num1.length();
        int n2 = num2.length();
        int[] product = new int[n1+n2];
        for(int i=n1-1;i>=0;i--){
            for(int j=n2-1;j>=0;j--){
                int index = n1+n2-i-j-2;
                product[index] += (num1.charAt(i)-'0') * (num2.charAt(j)-'0');
                product[index+1] += product[index]/10;
                product[index] %= 10;
            }
        }
        StringBuffer sb = new StringBuffer();
        for(int i=n1+n2-1;i>=0;i--){
            if(sb.length()==0&&product[i]==0) continue;
            sb.append(product[i]);
        }
        return sb.length()==0?"0":sb.toString();     
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值