Multiply String

29 篇文章 0 订阅
18 篇文章 0 订阅

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.

2015.3 update

一个很简洁的做法:https://leetcodenotes.wordpress.com/2013/10/20/leetcode-multiply-strings-%E5%A4%A7%E6%95%B4%E6%95%B0%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B9%98%E6%B3%95/comment-page-1/#comment-122

    public String multiply(String num1, String num2) {
        num1 = new StringBuilder(num1).reverse().toString();
        num2 = new StringBuilder(num2).reverse().toString();
        int[] d = new int[num1.length() + num2.length()];
        for (int i = 0; i < num2.length(); i++) {
            int b = num2.charAt(i)-'0';
            for (int j = 0; j < num1.length(); j++) {
                int a = num1.charAt(j)-'0';
                d[i+j] += a*b;
            }
        }
        int carry = 0;
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < d.length; i++) {
            int tmp = d[i]+carry;
            d[i] = tmp%10;
            carry = tmp/10;
            str.insert(0, d[i]);
        }
        if (carry > 0) {
            str.insert(0, carry);
        }

        while (str.length() > 0 && str.charAt(0) == '0') {
            str.deleteCharAt(0);
        }
        return str.toString().length() == 0 ? "0" : str.toString();
    }


    public String multiply(String num1, String num2) {
		int n1 = num1.length();
		int n2 = num2.length();
		int[] a = new int[n1];
		int[] b = new int[n2];
		for (int i = n1 - 1; i >= 0; i--) {
			a[i] = (int) (num1.charAt(n1 - i - 1) - '0');
		}
		for (int i = n2 - 1; i >= 0; i--) {
			b[i] = (int) (num2.charAt(n2 - i - 1) - '0');
		}

		int carry = 0;
		// store in reverse order
		List<Integer> result = new ArrayList<Integer>();

		for (int i = 0; i < n2; i++) { // outer, b numbers
			carry = 0;
			int mul = b[i];
			for (int j = 0; j < n1; j++) {
				int tmp = mul * a[j] + carry;
				if ((result.size() - 1) >= (i + j)) {
					carry = (result.get(i + j) + tmp) / 10;
					result.set(i + j, (result.get(i + j) + tmp) % 10);
				} else {
					result.add(tmp % 10);
					carry = tmp / 10;
				}
			}
			if (carry > 0) {
				result.add(carry);
			}
		}
		String ret = "";
		boolean isFirst = true;
		for (int i = result.size() - 1; i >= 0; i--) {
		    if (isFirst && result.get(i).equals(0)) {
		        continue;
		    }
			ret = ret + (char) (result.get(i) + '0');
			isFirst = false;
		}
		return ret.isEmpty() ? "0" : ret;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值