如何在 Java 中“预先增加”一个 BigInteger?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28264656/
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
How to 'pre increment' a BigInteger in Java?
提问by Andreas Hartmann
I have a for
loop with BigInteger
s, something like this:
我有一个for
带有BigInteger
s的循环,如下所示:
for(BigInteger a = BigInteger.valueOf(1); a.compareTo(someBigInteger); ++a) {...
Obviously I can't use the ++
operator on a non-primitive. How do I work around this?
显然,我不能++
在非原始对象上使用运算符。我该如何解决这个问题?
Also, I have to use BigInteger
in this scenario.
另外,我必须BigInteger
在这种情况下使用。
回答by Mureinik
++a
is a prefix increment, not a postfix increment, but in the context of a for-loop it doesn't really matter, as you ignore the return value of that statement anyway. In any event, this functionality could be acheieved by calling BigInteger.add
. Also note that compareTo
returns an int
, and since Java does not have implicit casts between int
s and boolean
s (like, e.g., C does), you'd have to compare its result to 0 to see if a
is smaller, larger or equal to someBigInteger
):
++a
是前缀增量,而不是后缀增量,但在 for 循环的上下文中它并不重要,因为您无论如何都会忽略该语句的返回值。无论如何,可以通过调用来实现此功能BigInteger.add
。另请注意,compareTo
返回 an int
,并且由于 Java 在int
s 和boolean
s之间没有隐式转换(例如,C 有),您必须将其结果与 0 进行比较,以查看是否a
小于、大于或等于someBigInteger
):
for (BigInteger a = BigInteger.ONE;
a.compareTo(someBigInteger) < 0;
a = a.add(BigInteger.ONE)) {...
回答by Manu
You cannot redefine the operator ++ to work with BigInteger, so the solution is the trivial one: 1) First declare a BigInteger and initialize it 2) In the loop, reassign the BigInteger (a new BigInteger is created when invoking the add method);
您不能重新定义运算符 ++ 以与 BigInteger 一起使用,因此解决方案是微不足道的:1)首先声明一个 BigInteger 并对其进行初始化 2)在循环中,重新分配 BigInteger(调用 add 方法时会创建一个新的 BigInteger) ;
private static final BigInteger LIMIT = new BigInteger("10");
public static void main(String[] args) {
new BigInteger("0");
for (BigInteger a = BigInteger.ZERO; a.compareTo(LIMIT) < 0; a = a.add(new BigInteger("1")))
System.out.println(a);
}
Refer to the documentation http://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#add(java.math.BigInteger)
请参阅文档http://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#add(java.math.BigInteger)
回答by Dipen Adroja
You can have it like this.
你可以这样拥有它。
for(BigInteger a = BigInteger.ONE; a.compareTo(someBigInteger); a=a.add(BigInteger.ONE)) {.
for(BigInteger a = BigInteger.ONE; a.compareTo(someBigInteger); a=a.add(BigInteger.ONE)) {.