Converting a big integer to decimal string

后端 未结 4 785
情话喂你
情话喂你 2020-12-19 20:40

At the risk of having this question voted as a duplicate, or even to have it closed, I had this question has come up.

Background

In \"normal

4条回答
  •  别那么骄傲
    2020-12-19 20:55

    I came across similar problem and did not find any solution to my liking, so came up with my owm. The idea is to convert your BigInt using whatever base to another BigInt with the base of power of 10, as large as possible but still smaller then your current base. That you can just convert by "digit" using system calls, and concatenate the result. So no explicit division ever involved, only hidden in system library functions. Still the overall complexity is quadratic (just like with the other division based solutions).

    friend std::ostream& operator<<(std::ostream& out, const BigInt_impl& x){
        using Big10 = BigInt_impl; // 1e9 is the max power of 10 smaller then BASE
        auto big10 = Big10(0);
        auto cm = Big10(1);
        for(size_t i = 0; i < x.digits.size(); ++i, cm *= BASE){
            big10 += cm*x.digits[i];
        }
        out << big10.digits.back();
        for(auto it = next(big10.digits.rbegin()); it != big10.digits.rend(); ++it){ 
            out << std::setfill('0') << std::setw(9) << *it;
        }
        return out;
    }
    

    Watch out for the magic constant 1e9 in this solution - this is just for my case of BASE = 2^32. Was lazy to do it properly.

    (and sorry, for C++, I just realized that qustion was about C, but still would like to leave the code here, maybe as an illustration of idea)

提交回复
热议问题