java中如何检查数字是否适合基本类型?
我需要进行一些输入验证,但遇到一个问题,我似乎找不到答案(即使使用谷歌)。问题很简单:我的输入有 2 个正整数,我需要检查它们的乘积是否适合 Java 中的 int 类型。
我的尝试之一是将乘积与 Integer.MAX_VALUE 进行比较,但似乎如果乘积对于整数来说太大,则值会变为负值。 我想通过改变符号来推断产品太大,但似乎如果产品“太大”,它会再次变得积极。
有人可以告诉我如何检测数字是否太大?
非常感谢!
I need do to some input validation but run into a question and I do not seem to find an answer (even with Google). The problem is simple: I have 2 positive integers on the input, and I need to check if their product fits int type in Java.
One of my attempts was to compare product with Integer.MAX_VALUE, but it seems if the product is too big for integer, value becomes negative.
I wanted to reason that product is too big by change in sign, but it seems if the product is "way too big" it will become positive again.
Could someone advise me how to detect if number becomes too big?
Many thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您正在做 UI,那么您可能并不特别着急。因此,您可以使用 BigInteger,然后根据 MAX_VALUE 测试产品。
If you are doing a UI, you are presumably in no particular hurry. So you could use a BigInteger and then test the product against MAX_VALUE.
将值转换为
int
并查看值是否相同。一个简单的检查看起来像如果回传时值相同,则不会丢失信息,您可以使用
int
值。Cast the value to
int
and see if the value is the same. A simple check looks likeIf the value is the same when cast back, there is no loss of information and you can use an
int
value.搜索并发现以下内容:
Searched and found the following:
您可以根据输入值创建 BigInteger并使用其 intValue() 方法进行转换。如果 BigInteger 太大而无法放入 int,则仅返回低位 32 位。因此,您需要将结果值与输入值进行比较,以确保它没有被截断。
You could create a BigInteger from your input value and use its intValue() method to convert. If the BigInteger is too big to fit in an int, only the low-order 32 bits are returned. So you need to compare the resulting value to your input value to ensure it was not truncated.