Meta interview question

Write a function to multiply two arbitrarily large integers.

Interview Answers

Anonymous

3 Oct 2010

BINT mult (BINT a, BINT b) { BINT sign = 1; if (a 0) { BINT a16 = a & 0xFF; while (b > 0) { BINT b16 = b & 0xFF; BINT tr = a16 * b16; r += tr >= 16; sn += 16; } a >>= 16; sn += 16; } return sign < 0 ? -r : r; }

2

Anonymous

3 Oct 2010

The solution I posted assumed that it is 32 bit computer. but if you are not sure about this, you have to use string to do multiplication.

Anonymous

17 Feb 2011

#define TO_INT(char) ((char) - '0') #define TO_CHAR(int) ((int) + '0')

Anonymous

17 Feb 2011

void Add(char str1[], char str2[], int offset) { int carry = 0; int len2 = strlen(str2); int i; for (i = 0; i < len2; i++) { int digit1 = TO_INT(str1[i + offset]); int digit2 = TO_INT(str2[i]); int result = digit1 + digit2 + carry; str1[i + offset] = TO_CHAR(result % 10); carry = result / 10; } while (carry != 0) { int digit = TO_INT(str1[i]); int result = digit + carry; str1[i + offset] = TO_CHAR(result % 10); carry = result / 10; } } char *Multiply(char str1[], char str2[]) { int len1 = strlen(str1); int len2 = strlen(str2); int product_len = len1 + len2; char *product = new char[product_len + 1]; for (int i = 0; i < product_len; i++) product[i] = '0'; product[product_len] = '\0'; int partial_len = len1 + 1; char partial[partial_len + 1]; for (int i = 0; i < partial_len; i++) partial[i] = '0'; partial[partial_len] = '\0'; for (int i = 0; i < len2; i++) { int digit2 = TO_INT(str2[i]); int carry = 0; int j; for (j = 0; j < len1; j++) { int digit1 = TO_INT(str1[j]); int result = digit1 * digit2 + carry; partial[j] = TO_CHAR(result % 10); carry = result / 10; } partial[j] = TO_CHAR(carry); Add(product, partial, i); } return product; }

Anonymous

31 Jan 2011

The below function 'multiple', can multiply integers (represented as strings) void strrev(string& s) { for(int i=0;i s2.size())? s1.size() : s2.size(); for(int i=0;i= i+1 )? s1.at(idx)-'0' : 0 ; unsigned int x2 = (s2.size() >= i+1 )? s2.at(idx)-'0' : 0 ; unsigned int x = carryOver + x1 + x2; //cout=0;--i){ char c = s1.at(i); //cout<<"ABC:"<