Multiply Strings

来源:互联网 发布:党员干部必知的新词 编辑:程序博客网 时间:2024/05/16 19:14

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.

说明:模拟手工计算两个整数的乘积,注意每轮乘积最高位的进位和乘积为0的情况。

代码:

char* multiply(char* num1, char* num2) {    char *zero = "0";    if(strcmp(num1, zero) == 0 || strcmp(num2, zero) == 0)  return zero;    int len1 = strlen(num1), len2 = strlen(num2);   //逆序存放乘积    char *ret = (char *)malloc(sizeof(char) * (len1+len2+1));        memset(ret, '0', sizeof(char) * (len1+len2+1));    int i = 0, j = 0;    for(i = 0; i <= len1-1; i++)    {    //乘数为0则跳过这次循环,开始下一次循环        if(num1[len1-1-i] == '0')    continue;        int carry = 0;        int n1 = num1[len1-1-i] - '0';        for(j = 0; j <= len2-1; j++)        {            int n2 = num2[len2-1-j] - '0';            int sum = n1 * n2 + ret[i+j] - '0' + carry;            carry = sum / 10;            ret[i+j] = sum % 10 + '0';        }        if(carry)   ret[i+len2] = carry + '0';    }    ret[len1+len2] = '\0';  //  printf("%s\n", ret);    char *p = ret, *q = &ret[len1+len2-1];    char tmp;    //将逆序的乘积转换成正序    while(p < q)    {        tmp = *p;        *p = *q;        *q = tmp;        p++;        q--;    }    //如100*100,再ret所指字符数组里原来存放"000010",翻转后变成"010000",需要去掉开头的'0'    if(*ret == '0')        return ret+1;    else        return ret;}
0 0