public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// Start typing your Java solution below
// DO NOT write main() function
ListNode head = null;
ListNode next = null;
ListNode cur = null;
int sum = 0;
while(l1 != null && l2 != null){
int total = sum + l1.val + l2.val;
sum = total / 10;
int value = total %10;
if(head == null){
head = new ListNode(value);
cur = head;
}else{
next = new ListNode(value);
cur.next = next;
cur = next;
}
l1 = l1.next;
l2 = l2.next;
}
while(l1 != null){
int total = sum + l1.val;
sum = total / 10;
int value = total %10;
if(head == null){
head = new ListNode(value);
cur = head;
}else{
next = new ListNode(value);
cur.next = next;
cur = next;
}
l1 = l1.next;
}
while(l2 != null){
int total = sum + l2.val;
sum = total / 10;
int value = total %10;
if(head == null){
head = new ListNode(value);
cur = head;
}else{
next = new ListNode(value);
cur.next = next;
cur = next;
}
l2 = l2.next;
}
if(sum > 0){
next = new ListNode(sum);
cur.next = next;
cur = next;
}
return head;
}Add two numbers
最新推荐文章于 2024-08-12 10:14:14 发布
本文提供了一个Java方法实现两个链表表示的大整数相加的功能。通过遍历两个链表,逐位相加并考虑进位,最终返回一个新的链表作为计算结果。该方法能够处理不同长度的输入链表。
506

被折叠的 条评论
为什么被折叠?



