leetcode:Multiply Strings(JAVA)

模拟手乘加法实现
代码:


    public String multiply(String num1, String num2) {
        int len1 = num1.length(), len2 = num2.length();
        if (len1 <= 0 && len2 <= 0) 
            return "";

        String res = "";
        String tempRes = "";
        int temp = 0, jinwei = 0;
        for (int i = len1 - 1; i >= 0; i--) {
            if (num1.charAt(i) == '0')
                continue;
            for (int j = len2 - 1; j >= 0; j--) {//
                temp = (num1.charAt(i) - 48) * (num2.charAt(j) - 48) + jinwei;
                if (temp > 9) {
                    jinwei = temp / 10;
                    tempRes = temp % 10 + tempRes;
                } else {
                    tempRes = temp + tempRes;
                    jinwei = 0;
                }
            }
            if (jinwei != 0)
                tempRes = jinwei + tempRes;
            // 添加0
            if (!tempRes.equals("0")) {
                for (int j = i + 1; j < len1; j++) {
                    tempRes = tempRes + "0";
                }
                res = addition(res, tempRes);
            }

            tempRes = "";
            jinwei = 0;
        }
        if (res.isEmpty())
            return "0";
        return res;
    }
    // 加法
    public String addition(String num1, String num2) {
        int len1 = num1.length(), len2 = num2.length();
        if (len1 <= 0 && len2 <= 0) {
            return "";
        }
        String res = "";
        int maxLen = len1 > len2 ? len1 : len2;
        int temp = 0, jinwei = 0;
        int index2 = len2 - 1;
        for (int i = len1 - 1; i >= 0; i--) {
            if (index2 >= 0) {
                temp = num1.charAt(i) + num2.charAt(index2--) - 96 + jinwei;
                // 处理进位
                if (temp > 9) {
                    jinwei = 1;
                    res = temp % 10 + res;
                } else {
                    res = temp + res;
                    jinwei = 0;
                }
            } else {
                temp = num1.charAt(i) - 48 + jinwei;
                if (temp > 9) {
                    jinwei = 1;
                    res = temp % 10 + res;
                } else {
                    res = temp + res;
                    jinwei = 0;
                }
            }
        }

        if (index2 >= 0) {
            for (int i = index2; i >= 0; i--) {
                temp = num2.charAt(i) - 48 + jinwei;
                if (temp > 9) {
                    jinwei = 1;
                    res = temp % 10 + res;
                } else {
                    res = temp + res;
                    jinwei = 0;
                }
            }
        }
        if (jinwei!=0)
            res = jinwei+res ;
        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值