/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// Start typing your Java solution below
// DO NOT write main() function
if (l1 == null && l2 == null)
return null;
ListNode result = new ListNode(0);
ListNode current = result;
int carry = 0;
int value = 0;
while (l1 != null && l2 != null) {
value = l1.val + l2.val + carry;
current.next = new ListNode(value % 10);
current = current.next;
carry = value / 10;
l1 = l1.next;
l2 = l2.next;
}
while (l1 != null) {
value = l1.val + carry;
current.next = new ListNode(value % 10);
current = current.next;
carry = value / 10;
l1 = l1.next;
}
while (l2 != null) {
value = l2.val + carry;
current.next = new ListNode(value % 10);
current = current.next;
carry = value / 10;
l2 = l2.next;
}
if (carry != 0)
current.next = new ListNode(1);
current = result;
result = result.next;
return result;
}
}Add Two Numbers
最新推荐文章于 2024-08-12 10:14:14 发布
本文介绍了一种解决两数相加问题的方法,通过使用链表数据结构来表示两个非负整数,并实现了它们的相加。文章详细阐述了算法步骤:遍历两个链表,逐位相加并处理进位,直至链表结束。
500

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



