How to implement big int in C++

前端 未结 13 2076
攒了一身酷
攒了一身酷 2020-11-22 07:48

I\'d like to implement a big int class in C++ as a programming exercise—a class that can handle numbers bigger than a long int. I know that there are several open sou

13条回答
  •  不知归路
    2020-11-22 08:19

    I'm not convinced using a string is the right way to go -- though I've never written code myself, I think that using an array of a base numeric type might be a better solution. The idea is that you'd simply extend what you've already got the same way the CPU extends a single bit into an integer.

    For example, if you have a structure

    typedef struct {
        int high, low;
    } BiggerInt;
    

    You can then manually perform native operations on each of the "digits" (high and low, in this case), being mindful of overflow conditions:

    BiggerInt add( const BiggerInt *lhs, const BiggerInt *rhs ) {
        BiggerInt ret;
    
        /* Ideally, you'd want a better way to check for overflow conditions */
        if ( rhs->high < INT_MAX - lhs->high ) {
            /* With a variable-length (a real) BigInt, you'd allocate some more room here */
        }
    
        ret.high = lhs->high + rhs->high;
    
        if ( rhs->low < INT_MAX - lhs->low ) {
            /* No overflow */
            ret.low = lhs->low + rhs->low;
        }
        else {
            /* Overflow */
            ret.high += 1;
            ret.low = lhs->low - ( INT_MAX - rhs->low ); /* Right? */
        }
    
        return ret;
    }
    

    It's a bit of a simplistic example, but it should be fairly obvious how to extend to a structure that had a variable number of whatever base numeric class you're using.

提交回复
热议问题