TypechoJoeTheme

IT技术分享

统计

[LeetCode 43] Multiply Strings[Java]

2018-01-08
/
0 评论
/
747 阅读
/
正在检测是否收录...
01/08

1. 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.

2. Example

num1 = "13", num2="13"
Output: "169"

3. Code

public class LeetCode0043 {
    public String multiply(String num1, String num2) {
        if (num1 == null || num1.length() == 0 || num2 == null || num2.length() == 0) {
            return "0";
        }

        int[] sum = new int[num1.length() + num2.length() - 1];

        for (int i = num1.length() - 1; i >= 0; i--) {
            for (int j = num2.length() - 1; j >= 0; j--) {
                sum[i + j] += (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
            }
        }

        StringBuilder sb = new StringBuilder();
        int carry = 0;
        for (int i = sum.length - 1; i >= 0; i--) {
            sum[i] += carry;
            carry = sum[i] / 10;
            sb.append(sum[i] % 10);
        }

        while (carry != 0) {
            sb.append(carry % 10);
            carry /= 10;
        }

        while (sb.length() > 1 && sb.charAt(sb.length() - 1) == '0') {
            sb.deleteCharAt(sb.length() - 1);
        }

        return sb.reverse().toString();
    }

    public static void main(String[] args) {
        LeetCode0043 leetcode = new LeetCode0043();
        System.out.println(leetcode.multiply("13", "13"));
    }
}
Math
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1376/(转载时请注明本文出处及文章链接)