我正在设计一个名为HugeInteger的类-它使用40个元素的数字数组来存储整数。我提供了一个名为parse的方法,它接收一个字符串,提取每个数字,如下面的代码片段所示。我还提供了add方法,它接收一个HugeInteger类的对象来做加法。为添加提供的方法不像建议的那样工作,我希望你能在一个解决方案中帮助我。附言:我注意到之前有人问过一些类似的问题,但这对我没有帮助。
private int [] integerDigits = new int[SIZE];
//constructor that enables an object of class to be initialised when it is declared
public HugeInteger(String stringOfIntegers)
{
setOfIntegers = stringOfIntegers;
}//end of constructor
private int[] parseFunction (String str)
{
for (int i = 0; i < str.length(); i++)
{
char ch = str.charAt(i);
if (Character.isDigit(ch))
integerDigits[i] = Character.getNumericValue(ch);
else
integerDigits[i] = 0;
}
return integerDigits;
}//end of method parseFunction
public HugeInteger addFunction(HugeInteger number)
{
parseFunction(setOfIntegers);
return new HugeInteger(setOfIntegers +number.parseFunction(setOfIntegers));
}//end of method addFunction发布于 2012-03-29 06:48:01
错误在下面这一行中:
return new HugeInteger(setOfIntegers +number.parseFunction(setOfIntegers));因为setOfIntegers是一个字符串,所以+符号并不意味着它们之间的相加,而是它们之间的连接(将它们写回原处)。因此,当5和6相加时,你会得到56而不是11,而不是调用构造函数,你需要像在纸上一样实现加法,从后面到前面,使用一个变量来保存进位数。
示例:
99
+ 11
0 carry 1
10 carry 1
= 110此外,因为您总是使用40位数,并且从数组的前面开始,所以您的问题无法知道这些数字中有多少真正属于该数字,因此它无法区分"5“、"500”、"5000“等等。这是一个问题,因为parseFunction(5)=parseFunction(50)={5,0,0,0,...,0} (总共39个零),并且问题不知道如何对齐数字。最好向下循环("integerDigits40-i= Character.getNumericValue(ch);"),因为这样"5“就会变成0000...05,而"50”就会变成000050。
另一个小错误是
number.parseFunction(setOfIntegers)这应该是
number.parseFunction(number.setOfIntegers)https://stackoverflow.com/questions/9895034
复制相似问题