BigInteger 的 Java 解决方法
我正在研究一个场景,其中我必须在 Java 中实现 BODMAS,并且操作数可以有多达 1000 个数字。所以我选择通过以下方式实现它 - 我将中缀表达式(要实现 BODMAS 的表达式)转换为后缀 然后我通过解析它所具有的每个 BigInteger 来评估后缀表达式。 我在这次实施中取得了成功。
现在我知道我不能使用 BigInteger,只能使用 int、string 等基本数据类型。
我一直在思考如何做到这一点,坦率地说,还没有取得任何重大进展。
关于如何使用基本数据类型实现 BigInteger 的任何帮助或建议都会有很大帮助。
I was working on a scenario wherein i had to implement BODMAS in Java and the operands could have as many as 1000 digits. So i chose to implement it in the following manner -
I converted the infix expression (expression on which BODMAS was to be implemented) to postfix
And then i evaluated the postfix expression by parsing every BigInteger that it had.
I was successful in this implementation.
Now i get to know that I can not use BigInteger and have to make do with the basic data types like int,string, etc.
I have been thinking about how this could be done and to be frank, havent made any significant progress.
Any help or suggestions on how BigInteger can be implemented using the basic data types would be of great help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实现大整数的一种直接方法是将它们存储为十进制数字数组,例如。 1234 可以表示为:
您需要实现普通加法、减法、乘法、除法以及您需要的任何其他操作。
您可能会发现“反转”存储数字可能会更容易,因此将 1234 存储为:
更高级的实现将使用基数 2^32 或比基数 10 大得多的值。
A straightforward way to implement large integers is to store them as an array of decimal digits, eg. 1234 could be represented by:
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:
A more advanced implementation would use base 2^32 or something much larger than base 10.
这是来自 Open JDK 的 BigInteger 的免费实现。它受 GPL2 的保护(这是一个问题吗?)
,即使您无法复制和粘贴它,您也可以了解如何在 int[] 数组中存储和操作这些位。
另一种选择可能是来自 CERN 的 colt 库。至少它可以处理巨大的位字段。
编辑
在找出BODMAS的含义后(认为它是一种密码算法或其他东西,并且必须在特殊且有限的JDK上完成;-))),我猜小马的建议是不合适的;)
我不会删除这个答案,尽管现在我认为,p1NG 对于使用(或重新实现)BigInteger 没有“法律”限制...
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...