如何在 C++ 中实现 big int [英] How to implement big int in C++

查看:42
本文介绍了如何在 C++ 中实现 big int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 C++ 中实现一个 big 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:

  1. 数学运算符:+、-、/、*, % 不要忘记你的班级可能在运算符,运算符可以是链式,操作数之一可以是 int、float、double 等.

  1. 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.

转化/演员:弄清楚什么类型/类你的大整数类应该可以转换为,和如何正确处理转换.一个快速列表将包括 double 和 float,并且可能包括 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++ 中实现 big int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆