Add Two Numbers
Add Two Numbers
问题:
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
思路:
归并排序 最后面的操作而已
我的代码:
public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1 == null) return l2; if(l2 == null) return l1; int plus = 0; ListNode dummy = new ListNode(0); ListNode cur = dummy; while(l1 != null && l2 != null) { int val = plus + l1.val + l2.val; if(val >= 10) { ListNode node = new ListNode(val-10); cur.next = node; plus = 1; } else { ListNode node = new ListNode(val); cur.next = node; plus = 0; } l1 = l1.next; l2 = l2.next; cur = cur.next; } while(l1 != null) { int val = plus + l1.val; if(val >= 10) { ListNode node = new ListNode(val-10); cur.next = node; plus = 1; } else { ListNode node = new ListNode(val); cur.next = node; plus = 0; } l1 = l1.next; cur = cur.next; } while(l2 != null) { int val = plus + l2.val; if(val >= 10) { ListNode node = new ListNode(val-10); cur.next = node; plus = 1; } else { ListNode node = new ListNode(val); cur.next = node; plus = 0; } l2 = l2.next; cur = cur.next; } if(plus != 0) { ListNode node = new ListNode(1); cur.next = node; } return dummy.next; } }
学习之处:
- 思路很简单,不过有两个地方可以进行简化,使代码看起来更加整洁 carry的获得方法,可以改成如下所示:
int sum = carry + l1.val + l2.val; point.next = new ListNode(sum % 10); carry = sum / 10;
posted on 2015-04-02 15:18 zhouzhou0615 阅读(159) 评论(0) 编辑 收藏 举报