首页 > 代码库 > leetcode 2 Add Two Numbers

leetcode 2 Add Two Numbers

public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode tn = null;
ListNode tl = new ListNode(0);
ListNode rl = tl;
int f = 0, s = 0, up = 0;
while (true) {

if (l1 != null) {
f = l1.val;
} else {
f = 0;
}

if (l2 != null) {
s = l2.val;
} else {
s = 0;
}

int sum = f + s + up;
if (sum < 10) {
tn = new ListNode(sum);
up = 0;
} else {
tn = new ListNode(sum%10);
up = 1;
}

tl.next = tn;
tl = tl.next;


if (l1 != null) {
l1 = l1.next;
}

if (l2 != null) {
l2 = l2.next;
}

if (l1 == null && l2 == null) {
if (up == 1) {
tn = new ListNode(up);
tl.next = tn;
}
break;
}
}

return rl.next;
}
}

技术分享

leetcode 2 Add Two Numbers