我一直在尝试编写一个小的BigInt类作为练习。我想把它作为bools的deque来实现,它代表二进制数字的数字。例如:1234变为=> 0100 0011 0010 0001.正如您所注意到的,我以相反的顺序保留数字的数字,但这些数字顺序正确。
这使得构建课程变得非常快,但操作变得如此棘手,我无法弄清楚如何去做。到目前为止,我有这个:
// Start from proper order + 3, because we store digits in reverse order.
BigInt operator+(int x) {
BigInt res(*this);
show_rep(res);
unsigned bit_place = BIT_FOR_DIGITS - 1;
auto res_it = res.num.begin() + bit_place;
bool carry = 0;
while (x | carry) {
if (res_it != res.num.end() && res_it + 1 == res.num.end()) {
for (int i = 0; i < BIT_FOR_DIGITS; ++i)
res.num.push_back(0);
}
bool res_prev = *res_it;
// combine bits with carry in
*res_it ^= (x & 1) ^ carry;
// figure out the carry out
carry = ((res_prev ^ (x & 1)) & carry) | (res_prev & (x & 1));
if (!bit_place) {
// because we do the operations from the rightmost bit to the left
// Ex: 1001 => 9, we start from right to left.
res_it += 2 * BIT_FOR_DIGITS - 1;
bit_place = BIT_FOR_DIGITS - 1;
}
else {
--bit_place;
--res_it;
}
x >>= 1;
}
show_rep(res);
return res;
}
BIT_FOR_DIGITS是4的宏。以上是硬件按位求和运算的简单实现。但是,我面临的问题是以下情况: