Skip to content

Instantly share code, notes, and snippets.

@shanehou
Created January 29, 2016 10:16
Show Gist options
  • Save shanehou/c3cc35c4cf33b28b5130 to your computer and use it in GitHub Desktop.
Save shanehou/c3cc35c4cf33b28b5130 to your computer and use it in GitHub Desktop.
Multiply Strings
char* multiply(char* num1, char* num2) {
if (!num1 || !num2) return NULL;
if (num1[0] == '0' || num2[0] == '0') return "0";
int len1 = strlen(num1), len2 = strlen(num2);
if (len1 == 1 && num1[0] == '1') return num2;
if (len2 == 1 && num2[0] == '1') return num1;
char *result = malloc((len1+len2)*sizeof(char));
memset(result, '0', (len1+len2)*sizeof(char));
for (int i = len1-1; i >= 0; i--) {
int carry = 0;
for (int j = len2-1; j >= 0; j--) {
int sum = (result[i+j+1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry;
result[i+j+1] = sum % 10 + '0';
carry = sum / 10;
}
result[i] += carry;
}
int i = 0;
while (result[i] == '0') i++;
return &result[i];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment