LeetCode 2 Add Two Numbers

来源:互联网 发布:韦斯利马修斯生涯数据 编辑:程序博客网 时间:2024/06/11 19:08

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

其中7=2+5;0=4+6;8=3+4+1(进位).

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {ListNode result = new ListNode(0);ListNode pointer = result;int flag = 0;while (l1 != null || l2 != null) {if (l1 != null) {flag += l1.val;l1 = l1.next;}if (l2 != null) {flag += l2.val;l2 = l2.next;}pointer.next = new ListNode(flag % 10);pointer = pointer.next;flag /= 10;}pointer.next = flag == 1 ? new ListNode(1) : null;return result.next;}

1 0
原创粉丝点击