文章目录
- 1. 题目描述
- 2. 解题代码
1. 题目描述
链接:https://leetcode.cn/problems/add-two-numbers/
2. 解题代码
public ListNode AddTwoNumber(ListNode l1, ListNode l2)
{ListNode head = new ListNode();ListNode cur = head;int carry = 0;while (l1 != null || l2 != null){int val1 = l1 == null ? 0 : l1.val; int val2 = l2 == null ? 0 : l2.val; // 求出商和余数int sum = val1 + val2 + carry;carry = sum / 10;sum %= 10;cur.next = new ListNode(sum);// 更新链表指向cur = cur.next;if (l1 != null) l1 = l1.next;if (l2 != null) l2 = l2.next;}if (carry == 1) cur.next = new ListNode(1);return head.next;
}