How to implement big int in C++(如何在 C++ 中实现大 int)
问题描述
我想在 C++ 中实现一个大 int 类作为编程练习——一个可以处理大于 long int 的数字的类.我知道已经有几个开源实现,但我想自己编写.我正在尝试了解正确的方法是什么.
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 source implementations out there already, but I'd like to write my own. I'm trying to get a feel for what the right approach is.
我了解一般策略是将数字作为字符串获取,然后将其分解为较小的数字(例如单个数字),并将它们放入数组中.此时,实现各种比较运算符应该相对简单.我主要关心的是如何实现加法和乘法.
I understand that the general strategy is get the number as a string, and then break it up into smaller numbers (single digits for example), and place them in an array. At this point it should be relatively simple to implement the various comparison operators. My main concern is how I would implement things like addition and multiplication.
我正在寻找一种通用的方法和建议,而不是实际的工作代码.
I'm looking for a general approach and advice as opposed to actual working code.
推荐答案
大型 int 类需要考虑的事项:
Things to consider for a big int class:
数学运算符:+、-、/、*, % 不要忘记你的班级可能在运算符,运算符可以是链式,即其中一个操作数可以是 int、float、double 等.
Mathematical operators: +, -, /, *, % Don't forget that your class may be on either side of the operator, that the operators can be chained, that one of the operands could be an int, float, double, etc.
I/O 操作符:>>, <<这是你在哪里弄清楚如何正确地从用户输入创建你的类,以及如何格式化输出.
I/O operators: >>, << This is where you figure out how to properly create your class from user input, and how to format it for output as well.
转化/转换:弄清楚你的大整数是什么类型/类别类应该可以转换为,并且如何正确处理转换.一个快速列表将包括双精度和浮点数,并且可能包括 int (有适当的界限检查)和复杂(假设它可以处理范围).
Conversions/Casts: Figure out what types/classes your big int class should be convertible to, and how to properly handle the conversion. A quick list would include double and float, and may include int (with proper bounds checking) and complex (assuming it can handle the range).
这篇关于如何在 C++ 中实现大 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 中实现大 int


基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01