对于这个项目,我正在创建数组,每个数组有 50 个元素,每个元素的值在 0 到 9 之间,并在加法、减法、乘法和除法中使用这些称为“BigIntegers”的数组。有一些较小的方法称为 increment 和 decrement,我无法弄清楚。这是我所做的代码...
public class BigInteger {
int[] BigInteger = new int[50];
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//x BigInteger(): creates a BigInteger of all 0's x
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
public BigInteger() {
for (int i = 0; i < 50; i++) {
BigInteger[i] = 0;
}
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//x BigInteger(n): creates a BigInteger the size of n x
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
public BigInteger(int n) {
for (int i = 49; i > 0; i--) {
BigInteger[i] = n%10;
n = n/10;
}
BigInteger[0] = n;
}
public int[] getBigInteger() {
return BigInteger;
}
public BigInteger(BigInteger n) {
for(int i = 0; i < 50; i++) {
BigInteger[i] = n.getBigInteger()[i];
}
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//x print(): prints out each element of the BigInteger array x
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
public void print() {
int index = 0;
for (int i = 0; i < BigInteger.length; i++) {
if (BigInteger[i] == 0) { index = 0; }
else { index = i; break; }
}
for(int i = index; i < BigInteger.length; i++) {
System.out.print(BigInteger[i] + " ");
}
}
public void decrement() {
int last = BigInteger.length;
for(int i = last; i < 50; i++) {
if (i == 0) { }
else last = BigInteger[last] - 1;
}
}
public static void main(String args[]) {
BigInteger big = new BigInteger(50);
BigInteger big2 = new BigInteger();
BigInteger big3 = new BigInteger(602345812);
}
这些方法的功能是:
• void increment() --- 将调用对象的值增加 1
• void decrement() --- 将调用对象的值减 1
我花了很多时间试图找出这些看似简单的方法。有任何帮助或建议吗?谢谢我。
如果我很好地理解你的问题,你应该试试这个(@Andy Turner 和@Yang Li 的评论)作为起点:
public void increment() {
for (int i = BigInteger.length - 1; i; i--)
if (BigInteger[i] < 9) {
BigInteger[i]++;
for (int j = i + 1; j < BigInteger.length; j++)
BigInteger[j] = 0;
break;
}
else if (i == 0)
// cannot increment 9
}
public void decrement() {
for (int i = BigInteger.length - 1; i; i--)
if (BigInteger[i] > 0) {
BigInteger[i]--;
for (int j = i + 1; j < BigInteger.length; j++)
BigInteger[j] = 9;
break;
}
else if (i == 0)
// cannot decrement 0
}
这将增加/减少数组的最后一个int
元素BigInteger
,其中BigInteger.length - 1
是数组中最后一个元素的索引。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句