c++ - 如何在 C++ 中将大数字字符串转换为整数?

标签 c++ string integer long-integer

假设,我在 c++ 中输入了一个长字符串数字。我们必须对其进行数值运算。我们需要将其转换为 integer 或任何可能的操作方式,这些是什么?

string s="12131313123123213213123213213211312321321321312321213123213213";

最佳答案

看起来您要处理的数字对于任何标准整数类型来说都太大了,因此仅“转换”它不会给您带来很多好处。您有两个选择:

  1. (强烈推荐!)使用大整数库,例如gmp .此类库通常还提供解析和格式化大数字的函数。

  2. 自己实现大数字,例如使用 uintmax_t 数组来存储它们。您将不得不自己实现可能需要的各种算术,而这并不是一件容易的事。要解析数字,您可以使用 反转的 double dabble 实现。例如,这是我不久前用 C 编写的一些代码,您可以按原样 使用它,但您需要提供一些辅助函数,并且您可能希望使用 C++ 工具重写它,例如std::string 并将此处使用的 struct 替换为 std::vector —— 此处仅用于记录概念

    typedef struct hugeint
    {
        size_t s;       // number of used elements in array e
        size_t n;       // number of total elements in array e
        uintmax_t e[];
    } hugeint;
    
    hugeint *hugeint_parse(const char *str)
    {
        char *buf;
    
        // allocate and initialize:
        hugeint *result = hugeint_create();
    
        // this is just a helper function copying all numeric characters
        // to a freshly allocated buffer:
        size_t bcdsize = copyNum(&buf, str);
    
        if (!bcdsize) return result;
    
        size_t scanstart = 0;
        size_t n = 0;
        size_t i;
        uintmax_t mask = 1;
    
        for (i = 0; i < bcdsize; ++i) buf[i] -= '0';
    
        while (scanstart < bcdsize)
        {
            if (buf[bcdsize - 1] & 1) result->e[n] |= mask;
            mask <<= 1;
            if (!mask)
            {
                mask = 1;
                // this function increases the storage size of the flexible array member:
                if (++n == result->n) result = hugeint_scale(result, result->n + 1);
            }
            for (i = bcdsize - 1; i > scanstart; --i)
            {
                buf[i] >>= 1;
                if (buf[i-1] & 1) buf[i] |= 8;
            }
            buf[scanstart] >>= 1;
            while (scanstart < bcdsize && !buf[scanstart]) ++scanstart;
            for (i = scanstart; i < bcdsize; ++i)
            {
                if (buf[i] > 7) buf[i] -= 3;
            }
        }
    
        free(buf);
        return result;
    }
    

关于c++ - 如何在 C++ 中将大数字字符串转换为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45669521/

相关文章:

javascript - 正则表达式检测双引号外的模式

json - 如何将 JSON 响应值与 Postman 环境变量匹配?

c++ - Dll 未在 Firefox 中加载,但在自定义应用程序中加载

php - 字符串分配中的累积内存使用 : $a = $a . $b vs $a .= $b

c++ - 从多个并行可执行文件写入单个文件的最佳方法

c# - (C#) 提高自定义getBetweenAll的速度

c - 大整数程序。 X 乘法后停止

c - 如何使用整数的小数

c++ - Peterson 的 C++ 多线程算法

c++ - 假人的高内存使用率