我正在寻找有关Java任务的一些建议。我被要求做的是对存储在链表中的数字执行不同的操作,每个数字在一个单独的节点中。关键是编写一个程序,可以对非常大的数字进行算术运算。
我正在寻找帮助的特殊问题是编写一个比较两个数字的方法,类似于int的常规compareTo()方法。如果this.num<它应该返回-1。 num,+ 1,如果this.num> num,如果它们相等则为0。
让我感到困难的是,分配指定链接列表应以相反的顺序存储数字。例如,数字145的链接列表如下所示:
5 => 4 => 1 =>空
这样可以更容易地将数字加在一起但是在尝试比较时让我头疼。这是我提出的,评论解释了它应该如何运作。
public int compareTo(LLNum list)
{ // Compares two numbers.
// If the two numbers are of a different length, clearly the shortest is the smallest.
// If the two numbers are of equal length, call traverseToCompare to do the comparison.
if (this.len > list.len)
{
compareResult = 1;
}
else if (this.len < list.len)
{
compareResult = -1;
}
else if (this.len == list.len)
{
traverseToCompare(this.head, list.head);
}
return compareResult;
}
public void traverseToCompare(ListNode node1, ListNode node2)
{ // In the case that both numbers are of the same length, recursively traverse the list.
// compare each digit individually while unwinding the stack.
// Once two digits are found to be different, break out of the unwinding (Note: I could not find a way of breaking out)
// Since the dominant digit is at the tail end, this ensures the least number of comparisons.
if (node1 == null || node2 == null)
{ // Base case. Handles the case where both numbers are identical.
compareResult = 0;
return;
}
traverseToCompare(node1.getNext(), node2.getNext());
if (node1.getItem() > node2.getItem())
{
compareResult = 1;
}
if (node1.getItem() < node2.getItem())
{
compareResult = -1;
}
return;
}
数字反向排列是让我走向递归的原因。我以为我会递归遍历列表,然后比较出路上的每个数字,并以某种方式突破不同的第一个数字的递归。我意识到这不是使用递归的常用方法,但我不确定如何做到这一点。有没有办法在不抛出异常的情况下打破?我认为这可能有点过于草率。或者没有递归就如何做到这一点的任何建议?
请不要只给我一些代码来复制和粘贴。我只是想指向正确的方向。谢谢!
答案 0 :(得分:0)
如果我必须这样做,我会首先检查两个列表的长度(就像你一样)。如果它们相等,那么进行比较的更好方法是为每个列表创建一个迭代器。然后,您可以同时递增迭代器并比较链接列表中该位置的值。这样做,一旦确定一个包含比另一个更大的数字,就可以直接停止比较列表。
答案 1 :(得分:0)
最好的方法是遍历每个数字的列表并构建数字,然后比较2个数字。
从列表中构建数字的方法是
int i = 0
int f = 1
Do while GetNext() <> Null
i = i + GetCurrentItem() * f
f = f * 10
End Do
例如。如果数字是145,则列表将具有5-> 4-> 1
所以运行上面的代码
i = 0
f = 1
i = i + 5*1 = 5
f = f * 10 = 10
i = i + 4*10 = 45
f = f * 10 = 100
i = i + 1*100 = 145
f = f * 10 = 1000
因此i = 145。
答案 2 :(得分:0)
使用普通字符串会更容易;因为你可以存储任何长度的数据。但无论如何,要求是LinkedList:
现在数据按逆序存储;这意味着在完成整个列表之前,您无法确定compareTo
方法的响应,因为大多数重要数据都存储在最后位置。
5 --> 4 --> 1 == 145
1 --> 4 --> 5 == 541
因此,至少阅读;然后,您可以将值存储在字符串中,然后决定compareTo
方法结果。
traverseToCompare 方法。因此,您可以编写自己的算法来比较存储在 String 中的两个数字。
修改强> 如果不允许使用String
然后会建议你手动做同样的事情;迭代整个列表比较最后一个节点,如果最后一个节点相同则比较前一个节点,依此类推...
答案 3 :(得分:0)
在traverseToCompare中,你需要处理一些情况。 如果不使用递归,它会更好,更干净。 以下可以是解决方案
boolean areSame = true;
boolean digitDiffer = false;
int compareResult = 0;
int length = node1.length
for(int i=0; i<length; i++)
{
if(!digitDiffer && ((node1.getItem() == node2.getItem()))
{
continue
}
else
{
digitDiffer = true;
if(node1.getItem() >= node2.getItem())
{
compareResult = 1
}
else
{
compareResult = -1;
}
}
}
return compareResult;