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
Output: 7 -> 0 -> 8
比较简单的链表题,其实也是模拟题,模拟加法运算的过程,只需要留意最后可能多出来的进位不要忘记加上去就好了。
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummy = new ListNode(0); ListNode temp = dummy; int carry = 0, sum = 0; while(l1 != null && l2 != null) { sum = l1.val + l2.val + carry; carry = sum / 10; ListNode node = new ListNode(sum % 10); temp.next = node; temp = temp.next; l1 = l1.next; l2 = l2.next; } while(l1 != null) { // only one of these will be excuted sum = l1.val + carry; carry = sum / 10; ListNode node = new ListNode(sum % 10); temp.next = node; temp = temp.next; l1 = l1.next; } while(l2 != null) { sum = l2.val + carry; carry = sum / 10; ListNode node = new ListNode(sum % 10); temp.next = node; temp = temp.next; l2 = l2.next; } if(carry > 0) { // important here ListNode node = new ListNode(carry); temp.next = node; } return dummy.next; }
没有评论:
发表评论