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

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

问题描述

我想在C ++中实现一个大的int类作为编程练习。一个可以处理大于一个long int数字的类。我知道有几个开源实现已经有,但我想写我自己的。我想知道正确的方法是什么。



我知道一般的策略是获取数字作为字符串,然后分解成更小的数字(例如,单个数字),并将它们放在数组中。在这一点上,应当相对简单地实现各种比较运算符。我主要关心的是我将如何实现像加法和乘法。



我正在寻找一个一般的方法和建议,适用于实际的工作代码。

解决方案

一个大型整数类的考虑事项:


  1. 数学运算符:+, - ,/,
    *,%不要忘记你的类可能在
    运算符的两边,运算符可以是
    链接,操作数
    之一可以是int,float,double等。


  2. I / O操作符:>>, <这是
    ,其中你找出如何正确
    从用户输入创建类,以及如何格式化其输出。


  3. p> Conversions / Casts:找出
    什么类型/类你的大int
    类应该可以转换为和
    如何正确处理
    转换。快速列表
    包括double和float,可以
    包括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 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 appose to actual working code.

解决方案

Things to consider for a big int class:

  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.

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

  3. 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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