当前位置:网站首页>LeetCode43. String multiplication (this method can be used to multiply large numbers)

LeetCode43. String multiplication (this method can be used to multiply large numbers)

2022-08-11 05:45:00 FussyCat

leecode题链接:LeetCode43.字符串相乘

题目描述:

给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式.

示例 1:
输入: num1 = “2”, num2 = “3”
输出: “6”

示例 2:
输入: num1 = “123”, num2 = “456”
输出: “56088”

说明:
num1 和 num2 的长度小于110.
num1 和 num2 只包含数字 0-9.
num1 和 num2 均不以零开头,除非是数字 0 本身.
不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理.

解题思路:
字符串相乘,vertical multiplication,Multiply and add while converting to characters,The solution is shown in the notes.
以下用C语言实现:

#define NUM(ch) ((ch) - '0')
#define CHAR(n) ((n) + '0')

char * multiply(char * num1, char * num2){
    
    if (num1 == NULL || num2 == NULL) {
    
        return NULL;
    }
    int size1 = strlen(num1);
    int size2 = strlen(num2);
    if ((size1 == 1 || size2 == 1) && (num1[0] == '0' || num2[0] == '0')) {
     /* One of the two numbers is0,则乘积为0 */
        return "0";
    }
    char *result = (char *)malloc(size1 + size2 + 1);
    memset(result, '0', size1 + size2 + 1);

    int i, j, tmp0, tmp1;
    result[size1 + size2] = '\0';
    for (i = size1 - 1; i >= 0; i--) {
     /* 从个位数开始算 */
        for (j = size2 - 1; j >= 0; j--) {
      /* 从个位数开始算 */
            tmp1 = NUM(result[i + j + 1]) + NUM(num1[i]) * NUM(num2[j]); /* 第i位的num1和第j位的num2相乘, tmp1最大为两位数 */
            result[i + j + 1] = CHAR(tmp1 % 10); /* The single digit of a two-digit number */
            tmp0 = tmp1 / 10 + NUM(result[i + j]); /* Tens of two digits+The number currently saved,求和 */
            result[i + j] = CHAR(tmp0 % 10); /* and single digits */
            if ( i + j - 1 >= 0) {
    
                result[i + j - 1] = CHAR(tmp0 / 10 + NUM(result[i + j - 1]));  /* and the ten digits+The number currently saved,求和 */
            }
        }
    }

    for (i = 0; i < size1 + size2; i++) {
    
        if (result[i] != '0') {
     /* Remove the prefix as 0的情况,Find the last one in the prefix0的位置 */
            break;
        }
    }

    return (result + i);
}
原网站

版权声明
本文为[FussyCat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/223/202208110512507146.html