Leetcode : Multiply String

题目连接:https://leetcode.com/problems/multiply-strings/#/description
题目如下:
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.
Subscribe to see which companies asked this question.

这道题基本在一上大一的时候就会遇见,是非常老(经典)的题目了,但是如何做的比较优雅,就是需要动一下脑筋,废话不多说,下面给出代码,也希望和大家一起讨论,更好的解题方法。

public class MultiplyString {

//char[] 反转
    private void reverse(char[] str){
        int start = 0, end = str.length-1;
        char temp;
        while(start<end){
            temp = str[start];
            str[start] = str[end];
            str[end] = temp;
            start++;
            end--;
        }
    }

    public String multiply(String num1, String num2) {
        char[] char1 = num1.toCharArray();
        char[] char2 = num2.toCharArray();
        reverse(char1);
        reverse(char2);
        return muliplyHelper(char1,char2);
    }

    /**
     * 此时num1,num2已经反转
     * @param num1
     * @param num2
     * @return
     */
    private String muliplyHelper(char[]num1,char[]num2){
        int temp=0;
        int[] result = new int[num1.length+num2.length];
        for(int i=0;i<num1.length;i++){
            for(int j=0;j<num2.length;j++){
                temp = (num1[i]-'0')*(num2[j]-'0')+result[i+j];
                result[i+j] = temp%10;
                result[i+j+1] += temp/10; //这里需要注意!
            }
        }
        boolean isFirst = true;
        StringBuilder builder = new StringBuilder();
        for(int i=num1.length+num2.length-1;i>=0;i--){
            if(result[i]==0&&isFirst){
                continue;
            }else{
                if(isFirst)
                    isFirst= false;
                builder.append(result[i]);
            }
        }
        if(isFirst)
            builder.append("0");
        return builder.toString();
    }

    public static void main(String[]args){
        MultiplyString multiplyString = new MultiplyString();
        multiplyString.multiply("0","100");
    }
}

下面给出运行结果:

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值