*LeetCode-Multiply Strings

22 篇文章 0 订阅
16 篇文章 0 订阅

就像正常的乘法一样 存下来结果的每一位 存成一个int array 然后处理一下大于十的 累加到前一位

然后就concat成string 但是注意前面很多0 不能加 但是假如全是0 就要返回0

public class Solution {
    public String multiply(String num1, String num2) {
        int len1 = num1.length();
        int len2 = num2.length();
        int [] products = new int [ len1 + len2 ];
        for ( int i = len1 - 1; i >= 0; i -- ){
            for ( int j = len2 - 1; j >= 0; j -- ){
                products[ i + j + 1 ] += ( num1.charAt(i) - '0' ) * ( num2.charAt(j) - '0' );
            }
        }
        int carry = 0;
        for ( int i =  products.length - 1; i >= 0; i -- ){
            products[ i ] += carry;
            carry = products[i] / 10;
            products[ i ] %= 10;
        }
        StringBuilder sb = new StringBuilder ();
        if ( carry != 0 )
            sb.append ( Integer.toString(carry) );
        int pos = 0;
        while ( pos < products.length && products[pos] == 0 ){
            pos ++;
        }
        if ( pos == products.length )
            return "0";
        for (; pos < products.length; pos ++ ){
            sb.append ( Integer.toString(products[pos]) );
        }
        return sb.toString();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值