2

我正在研究一个场景,我必须在 Java 中实现 BODMAS,并且操作数可能有多达 1000 个数字。所以我选择以下列方式实现它——我将中缀表达式(将在其上实现 BODMAS 的表达式)转换为后缀然后我通过解析它拥有的每个 BigInteger 来评估后缀表达式。我在这个实施中是成功的。

现在我知道我不能使用 BigInteger 并且必须使用基本数据类型,如 int、string 等。

我一直在考虑如何做到这一点,坦率地说,还没有取得任何重大进展。

关于如何使用基本数据类型实现 BigInteger 的任何帮助或建议都会有很大帮助。

4

2 回答 2

2

A straightforward way to implement large integers is to store them as an array of decimal digits, eg. 1234 could be represented by:

int[] bignum = new int[] {1, 2, 3, 4};

You would need to implement longhand addition, subtraction, multiplication, division, and whatever else you need.

You may find that storing the numbers "reversed" might be easier, so store 1234 as:

int[] bignum = new int[] {4, 3, 2, 1};

A more advanced implementation would use base 2^32 or something much larger than base 10.

于 2010-01-07T17:35:41.663 回答
2

Here is a free implementation of BigInteger from Open JDK. It's covered by GPL2 (is that a problem?)

And even if you can't copy&paste it, you can learn how the bits are stored and manipulated in an int[] array.

An alternative may be the colt library from CERN. At least it can handle giant bit fields.

Edit

After finding out the meaning of BODMAS (thought it was a cipher algorithm or something else and had to be done on a special and limited JDK ;-)) ), I guess the colt advice is not appropriate ;)

I don't delete this answer, even though now I think, p1NG has no 'legal' restriction against using (or reimplementing) BigInteger...

于 2010-01-07T17:43:59.413 回答