You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.題目的意思是,輸入兩個ListNode l1和l2,每個ListNode表明一個‘反序’數字。例如4->3->2表明的是234。咱們的目的是求出兩個數字的加和,並以一樣的ListNode形式返回。假設每一個listnode都不會存在在首位的0,除非數字自己就是0.node
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.git
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode p = l1; ListNode q = l2; ListNode head = new ListNode(0); ListNode curr = head; int sum =0; while(p != null || q != null){ sum = sum / 10; if(p != null){ sum += p.val; p = p.next; } if(q != null){ sum += q.val; q = q.next; } curr.next = new ListNode(sum % 10); curr = curr.next; } if(sum >= 10){ curr.next = new ListNode(1); } return head.next; }