Leetcode 43. Multiply Strings

来源:互联网 发布:飞行器动力知乎 编辑:程序博客网 时间:2024/05/18 06:21

43. Multiply Strings

Total Accepted: 75018 Total Submissions: 300195 Difficulty: Medium

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.

Hide Company Tags
 Facebook Twitter
Hide Tags
 Math String
Hide Similar Problems
 (M) Add Two Numbers (E) Plus One (E) Add Binary

准备某公司面试的时候碰到的面经题,刚好做过就看了看发上来了。

之前AC的代码很简洁,新建个数组,size是俩 string size之和

12 - length 2

13 - length 2

new int[4]

外层循环 i = 1, 0

内层循环 j = 1, 0

p[1 + 1 + 1] += 6, p[1 + 0 + 1] += 2

p[0 + 1 + 1]+ =3, p[0+ 0 + 1]+ = 1 - > p[0, 1, 5, 6]

然后从后向前(低到高位)处理进位,没有超过10的,所以直接从头开始粘贴num输出,156。

public class Solution {    public String multiply(String num1, String num2) {        int n1 = num1.length(), n2 = num2.length();        int[] products = new int[n1 + n2];        for (int i = n1 - 1; i >= 0; i--) {            for (int j = n2 - 1; j >= 0; j--) {                int d1 = num1.charAt(i) - '0';                int d2 = num2.charAt(j) - '0';                products[i + j + 1] += d1 * d2;            }        }        int carry = 0;        for (int i = products.length - 1; i >= 0; i--) {            int tmp = (products[i] + carry) % 10;            carry = (products[i] + carry) / 10;            products[i] = tmp;        }        StringBuilder sb = new StringBuilder();        for (int num : products) sb.append(num);        while (sb.length() != 0 && sb.charAt(0) == '0') sb.deleteCharAt(0);        return sb.length() == 0 ? "0" : sb.toString();    }}


0 0
原创粉丝点击