代码之家  ›  专栏  ›  技术社区  ›  quietsamurai98

将64位以上的数组转换为10进制字符串

  •  0
  • quietsamurai98  · 技术社区  · 7 年前

    std::vector<bool> 我使用将位存储到一个以10为基数的字符串中。目前,我的算法是

    unsigned long long sum = 0LL;
    for(unsigned long long i=0; i<64LL && i<bit_list.size(); i++){
        if(bit_list[i]){
            sum |= 1LL << i;
        }
    }
    return std::to_string(sum);
    

    然而,这仅适用于2^64以下的数字,因为 std::to_string 和内置 unsigned long long

    2 回复  |  直到 7 年前
        1
  •  1
  •   Rob K    7 年前

    伪代码:

    string s;
    your_bitlist_class i;
    if ( i > 0 )
    {
        while ( i > 0 )
        {
            s.insert( 0, std::to_string( i % 10 ) );
            i /= 10;   
        }
    }
    else
    {
        s = "0";
    }
    

    优化留给读者作为练习。

        2
  •  0
  •   quietsamurai98    7 年前

    这是我发现的运行良好的算法。它不是超高效的,但它完成了工作。

    BigInt num_copy(this);
    std::vector<unsigned short> digits;
    digits.push_back(0);
    while(num_copy!=0){
        num_copy--;
        digits[0]++;
        unsigned long long i = 0LL;
        while(digits[i]==10){
            if(digits.size()==(i+1LL)){
                digits.push_back(0);
            }
            digits[i]=0;
            i++;
            digits[i]++;
        }
    }
    std::string outstr = "";
    for(unsigned long long i=0LL; i < digits.size(); i++){
        outstr = std::to_string(digits[i]) + outstr;
    }
    return outstr;