Microsoft Interview Question
here is the clue how to do this:
(refer to gmplib.org for mature implementations)
// basic data type
typedef unsigned long limb;
class BigInt {
limb *data; // stores digits
int n_limbs; // # of limbs (radix 2^32 digits)
int n_allocated; // # of limbs allocated
bool sign; // sign
public:
BigInt() :
data(0), n_limbs(0), n_allocated(0), sign(0) {
}
// constructs bigint from string
BigInt(const char *str);
// from integer
BigInt(int x) :
n_allocated(0), data(0) {
alloc_limbs(1);
data[0] = abs(x);
sign = (x < 0);
}
// adds to bigints: need special handling for signed operands
friend BigInt operator +(const BigInt& a, const BigInt& b) {
BigInt res;
int na = a.n_limbs, nb = b.n_limbs;
limb *pl = a.data, *ps = b.data, maxn = na, minn = nb;
if(nb > na) {
swap(pl, ps);
swap(maxn, minn);
}
res.n_limbs = maxn + 1;
res.alloc_limbs(res.n_limbs);
limb *pc = res.data;
int carry = 0;
for(int i = 0; i < minn; i++) {
limb x = *pl++, c = x + *ps++;
carry = (c < x) + carry; // adjust for carry
c += carry;
carry = (c < carry); // overflow if sum < summands
*pc++ = c;
}
// iterate over the high-order digits to update carry flag
for(int i = 0; i < maxn - minn; i++) {
limb c = carry + *pl++;
carry = (c < carry);
*pc++ = c;
}
*pc = carry; // add the leading carry
}
private:
// allocates space enough to store n limbs
void alloc_limbs(int n) {
if(n_allocated >= n)
return;
data = (limb *)malloc(n);
n_allocated = n;
}
};
Any clues on how to do it???
- Pavan B October 27, 2006