Multiply Strings

来源:互联网 发布:卓依婷 知乎 编辑:程序博客网 时间:2024/04/29 05:22

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.

Have you been asked this question in an interview? 

public class Solution {    public String multiply(String num1, String num2) {if (num1 == null || num2 == null) {return null;}// 不要用“==”,比较的是地址if (num1.equals("0") || num2.equals("0")) {    return "0";}int l1 = num1.length();int l2 = num2.length();int l3 = l1 + l2;int[] res = new int[l3];int carry = 0;for (int i = l1 - 1; i >= 0; i--) {int j = l2 - 1;//res[i + 1] += carry;carry = 0;for (; j >= 0; j--) {res[i + j + 1] += (num1.charAt(i) - '0')* (num2.charAt(j) - '0') + carry;carry = res[i + j + 1] / 10;res[i + j + 1] = res[i + j + 1] % 10;}//注意每一层内部循环结束,都要把carry 付值了。例如 123*456, 3*456以后000368,不把carry加到倒数第四位的话// carry 在下一层循环中就会被加到倒数第二位,则出错。同时每个内层循环开始,都要把carry 清0res[i + j +1] += carry;}//res[0] = carry;StringBuilder sb = new StringBuilder();int i = res[0] == 0 ? 1 : 0;for (; i < res.length; i++) {sb.append(res[i]);}return sb.toString();}}


0 0
原创粉丝点击