leetcode-Multiply Strings

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.
    • Converting the input string to integer is NOT allowed.
    • You should NOT use internal library such as BigInteger.

解析:主要是数组位置和乘法位置的关系图:

Multiplication

代码解析:package leetcode;

/*
 * 题目主要考察字符串的乘法运算!!!
 * 关键步骤:
 * 1、找好每一步乘法结果与结果数组(pos[])对应起来。每一次只在pos数组中进行运算!!!这样就涉及到两个char[]和一个int[]!!!
 * 2、每一步乘法的结果应该加上以前的进位!!那么变量有:进位变量pos[p2],当前存储乘法结果的变量cures,然后将这个结果拆分成十位+个位,存在pos两个位置里,然后循环的时候,同时往前走一步,p2 ->p1位置。
 * 3、最后构造String的时候使用StringBuilder,主要是用来判断第一个数是否为0!!
 */
public class MultiplyStrings {

    public static String multiply(String num1, String num2) {
        char[] ch1 = num1.toCharArray();
        char[] ch2 = num2.toCharArray();
        int len1 = num1.length();
        int len2 = num2.length();
        int[] pos = new int[len1 + len2];

        for (int j = len2 - 1; j >= 0; j--)
            for (int i = len1 - 1; i >= 0; i--) {
                int cures = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
                // 下标是往前运动的
                int p1 = i + j, p2 = i + j + 1;
                // 每一步的运算的子结果,为什么是p2?
                // 因为:这里的p2就是下一个循环的p1,而p1指向更前的位置
                // 在下一个循环加进位!!!!!!
                int sum = cures + pos[p2];

                // 对每个相邻的位进行运算
                pos[p1] += sum / 10;
                // 存储后面那一位(不再变化),前面的位很有可能向前进位,所有要+=
                pos[p2] = sum % 10;
            }
        // 这一步:array->string,有很多方法,其实底层都是构造string;
        StringBuilder sb = new StringBuilder();
        for (int p : pos)
            // 判断一下,当头为0时,就不用添加;
            if (!(sb.length() == 0 && p == 0))
                sb.append(p);
        return sb.length() == 0 ? "0" : sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(multiply("10", "11"));
    }
}

转载于:https://www.cnblogs.com/neversayno/p/5434690.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值