leetcode上的问题:https://leetcode.com/problems/add-two-numbers/ 我的解决方案导致超出时间限制,我无法理解我的代码有什么问题:
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int c = 0, j = 0;
ListNode temp3 = new ListNode(); //temp3 = null;
ListNode h = temp3;
int n;
while (l1 != null || l2 != null || c == 1) {
int s = 0;
if (l1 == null && l2 == null)
s = c;
else if (l1 == null)
s = l2.val + c;
else if (l2 == null)
s = l1.val + c;
else
s = l1.val + l2.val + c;
if (s > 9) {
c = s / 10;
s = s % 10;
}
ListNode node = new ListNode(s);
//System.out.println(node.val);
h.next = node;
if (l1 != null)
l1 = l1.next;
if (l2 != null)
l2 = l2.next;
h = h.next;
}
return temp3.next;
}
}
1条答案
按热度按时间wlzqhblo1#
看起来你从来没有重置过携带(
c
)回到0
.因此,一旦将其设置为非零值,循环将永远不会结束。
您应该将其重置为
0
在项目的每个迭代开始时while
环或者你可以改变
到