OR147. 字符串相乘
描述
给定两个数字(0-9)字符串(长度不限)求它们的乘积。输入描述
第一行为第一个数字字符串输出描述
乘积字符串示例1
输入:
123 20
输出:
2460
C 解法, 执行用时: 1ms, 内存消耗: 376KB, 提交时间: 2020-07-18
#include <stdio.h> #include <string.h> void GetMulti(char s1[], char s2[]) { int num1[1000], num2[1000]; int res[1000] = {0}; for (int i = 0; i < strlen(s1); ++i) { num1[strlen(s1) - i - 1] = s1[i] - '0'; } for (int i = 0; i < strlen(s2); ++i) { num2[strlen(s2) - 1 - i] = s2[i] - '0'; } for (int i = 0; i < strlen(s1); ++i) { for (int j = 0; j < strlen(s2); ++j) { res[i + j] += num1[i] * num2[j]; } } int tmp = 0; for (int i = 0; i <= strlen(s1) + strlen(s2) - 1; ++i) { res[i] += tmp; tmp = res[i] / 10; res[i] = res[i] % 10; } tmp = strlen(s1) + strlen(s2) - 1; while (res[tmp] == 0) { --tmp; } for (int i = tmp; i >= 0; --i) { printf("%d", res[i]); } printf("\n"); return; } int main() { char str1[1000], str2[1000]; gets(str1); gets(str2); GetMulti(str1, str2); return 0; }
C 解法, 执行用时: 2ms, 内存消耗: 228KB, 提交时间: 2019-04-12
#include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { int j, k, z; #define SIZE 1000 char str[SIZE+1]; scanf("%s", str); int int1[SIZE]; int number1; number1 = strlen(str); for (j = 0; j < number1; j++) { if (str[j] != '0') break; } for (k = j, z = 0; k < number1; k++, z++) { int1[z] = str[k] - '0'; } number1 = z; int int2[SIZE]; int number2; scanf("%s", str); number2 = strlen(str); for (j = 0; j < number2; j++) { if (str[j] != '0') break; } for (k = j, z = 0; k < number2; k++, z++) { int2[z] = str[k] - '0'; } number2 = z; int resPos; int int3[SIZE+SIZE]; int endResPos = sizeof(int3)/sizeof(int); for (k = 0; k < endResPos; k++) { int3[k] = 0; } for (k = 1; k <= number2; k++) { int numPos = k; int curNum = int2[number2 - k]; for (j = 1; j <= number1; j++) { int x = curNum * int1[number1 - j]; resPos = (endResPos-1) - (numPos-1) - (j-1); int3[resPos] += x; while (int3[resPos] >= 10) { int incr = int3[resPos]/10; int3[resPos] %= 10; resPos--; int3[resPos] += incr; } } } for (k = resPos; k < endResPos; k++) { printf("%d", int3[k]); } printf("\n"); return 0; }