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
解题思路:
本题解题思路与Add Binary一模一样,都是按位加,用flag记是否有进位,有是1,没有是0,不同的地方就是LinkedList的操作和String有一些区别,这点要特别注意!!当然我看到一个答案用的变量比我少,感觉更漂亮,也贴上来。
Java code
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode result = new ListNode(0); ListNode p = result; ListNode p1 = l1, p2 = l2; int flag = 0; while(p1 != null || p2 != null){ int v1 = 0, v2 = 0; if(p1 != null){ v1 = p1.val; p1 = p1.next; } if(p2 != null){ v2 = p2.val; p2 = p2.next; } int sum = v1+v2+flag; if(sum >= 10){ p.next = new ListNode(sum -10); flag = 1; }else { p.next = new ListNode(sum); flag = 0; } p = p.next; } if(flag == 1){ p.next = new ListNode(1); } return result.next; } }
或者
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int carry = 0; ListNode result = new ListNode(0); ListNode p1 = l1, p2 = l2, p3 = result; while(p1 != null || p2 != null){ if(p1 != null){ carry += p1.val; p1 = p1.next; } if(p2 != null){ carry += p2.val; p2 = p2.next; } p3.next = new ListNode(carry%10); p3 = p3.next; carry /= 10; } if(carry == 1){ p3.next = new ListNode(1); } return result.next; }
Reference:
1. http://www.programcreek.com/2012/12/add-two-numbers/