java java中BigInteger的%运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11586166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
% operator for BigInteger in java
提问by Saendra
How to use a%b
with big integers?
like
如何使用a%b
大整数?喜欢
...
BigInteger val = new BigInteger("1254789363254125");
...
boolean odd(val){
if(val%2!=0)
return true;
return false;
...
Eclipse says that operator % is undefined for BigInteger.
Eclipse 表示 BigInteger 的运算符 % 未定义。
Any ideas?
有任何想法吗?
回答by jrad
Like this:
像这样:
BigInteger val = new BigInteger("1254789363254125");
public boolean odd(BigInteger val) {
if(!val.mod(new BigInteger("2")).equals(BigInteger.ZERO))
return true;
return false;
}
Or as user Duncan suggested in a comment, we can take out the if statement altogether like so:
或者正如用户 Duncan 在评论中建议的那样,我们可以像这样完全删除 if 语句:
BigInteger val = new BigInteger("1254789363254125");
public boolean odd(BigInteger val) {
return !val.mod(new BigInteger("2")).equals(BigInteger.ZERO));
}
回答by David says Reinstate Monica
A much more efficient way is to check the last bit. If it is 0
(aka false
) the number is even, otherwise it is odd.
更有效的方法是检查最后一位。如果是0
(又名false
),则数字为偶数,否则为奇数。
public boolean odd(BigInteger i){
return i.testBit(0);
}
odd(BigInteger.valueOf(1));//true
odd(BigInteger.valueOf(2));//false
odd(BigInteger.valueOf(101));//true
odd(BigInteger.valueOf(100));//false
Also its less lines of code.
它的代码行也更少。
回答by SamCle88
回答by Polygnome
Use val.mod(2).
使用 val.mod(2)。
BigInteger is an object. You can't use arithmetic operators on objects, that works only with primitives.
BigInteger 是一个对象。你不能在对象上使用算术运算符,它只适用于基元。
% only works with java.lang.Integer because that is implicitly cast (actually, it is called unboxed) to int. But BigInteger can not be unboxed. unboxing / baxing (that means object to primitive / primitive to object conversion) only works with int, float, double, short and byte.
% 仅适用于 java.lang.Integer,因为它隐式转换(实际上,它被称为未装箱)为 int。但是 BigInteger 不能拆箱。拆箱/打包(即对象到原始/原始到对象的转换)仅适用于 int、float、double、short 和 byte。
回答by SJuan76
As BigInteger is a class and not a primitive*1, you do not use operators with it. Check the methods for BigInteger: http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigInteger.html#mod(java.math.BigInteger)
由于 BigInteger 是一个类而不是一个原始类型*1,因此您不要对它使用运算符。检查 BigInteger 的方法:http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigInteger.html#mod( java.math.BigInteger)
*1: In the case of Integer, Float, you can use operators because the JVM automatically converts the object to its primitive value (autoboxing)
*1:在Integer、Float的情况下,可以使用运算符,因为JVM会自动将对象转换为其原始值(自动装箱)