Multiply Strings

57 篇文章 0 订阅

Given two numbers represented as strings, return multiplication of the numbers as a string.

public class Solution {
    public String multiply(String num1, String num2) {
        if (num1 == null || num2 == null) {
            return null;
        }
        int len1 = num1.length(), len2 = num2.length();
        int len3 = len1 + len2;
        int i, j, product, carry;
        int[] num3 = new int[len3];
        for (i = len1 - 1; i >= 0; i--) {
            carry = 0;
            for (j = len2 - 1; j >= 0; j--) {
                product = carry + num3[i + j + 1] +
                    Character.getNumericValue(num1.charAt(i)) *
                    Character.getNumericValue(num2.charAt(j));
                num3[i + j + 1] = product % 10;
                carry = product / 10;
            }
            num3[i + j + 1] = carry;
        }
        /**
         *  num1=123 num2=456
         *  以上过程模拟num2*num1:
         *  	      4 5 6
         *        *   1 2 3
         *------------------  
         *          1 3 6 8
         *          9 1 2
         *------------------
         *		  1 0 4 8 8	
         *        4 5 6
         *------------------
         *        5 6 0 8 8         
         */
        StringBuilder sb = new StringBuilder();
        i = 0;
        while (i < len3 - 1 && num3[i] == 0) {
            i++;
        }
        while (i < len3) {
            sb.append(num3[i++]);
        }
        return sb.toString();
    }
    public static void main(String[] args) {
		Solution solution = new Solution();
		String res = solution.multiply("123", "456");
		System.out.println(res);
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值