标签:tostring convert 思路 trunc math input 代码 ret 存储
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Note:
num1
and num2
is < 110.num1
and num2
contain only digits 0-9
.num1
and num2
do not contain any leading zero, except the number 0 itself.不使用内建库实现大数乘法。
class Solution {
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) {
return "0";
}
int[] array = new int[num1.length() + num2.length()];
for (int i = 0; i < num1.length(); i++) {
for (int j = 0; j < num2.length(); j++) {
int x = num1.charAt(i) - ‘0‘;
int y = num2.charAt(j) - ‘0‘;
array[i + j + 1] += x * y;
}
}
int carry = 0;
for (int i = array.length - 1; i >= 0; i--) {
int sum = array[i] + carry;
array[i] = sum % 10;
carry = sum / 10;
}
StringBuilder sb = new StringBuilder();
// 第一个为0则不加入字符串中
for (int i = array[0] == 0 ? 1 : 0; i < array.length; i++) {
sb.append((char) (array[i] + ‘0‘));
}
return sb.toString();
}
}
/**
* @param {string} num1
* @param {string} num2
* @return {string}
*/
var multiply = function (num1, num2) {
if (num1 === ‘0‘ || num2 === ‘0‘) {
return ‘0‘
}
let product = new Array(num1.length + num2.length).fill(0)
for (let i = 0; i < num1.length; i++) {
for (let j = 0; j < num2.length; j++) {
product[i + j + 1] += num1[i] * num2[j]
}
}
for (let i = product.length - 1; i >= 0; i--) {
if (i > 0 && product[i] >= 10) {
product[i - 1] += Math.trunc(product[i] / 10)
product[i] %= 10
}
}
if (product[0] === 0) {
product = product.slice(1)
}
return product.join(‘‘)
}
参考
Black_Knight - LeetCode 43. Multiply Strings
标签:tostring convert 思路 trunc math input 代码 ret 存储
原文地址:https://www.cnblogs.com/mapoos/p/13205889.html