首页 > 其他 > 详细

Add two numbers

时间:2015-04-09 06:18:07      阅读:267      评论:0      收藏:0      [点我收藏+]

题目: 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

没啥好说的,类似与merge list的过程。对余下的list的操作可以合并,使代码看起来简洁。就是那个意思,体会一下。。。

 1     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
 2         ListNode A = l1;
 3         ListNode B = l2;
 4         int carry = 0;
 5         ListNode newHead = new ListNode(0);
 6         ListNode cur = newHead;
 7         while(A != null || B != null){
 8             if (A != null){
 9                 carry += A.val;
10                 A = A.next;
11             }
12             if (B != null){
13                 carry += B.val;
14                 B = B.next;
15             }
16             cur.next = new ListNode(carry % 10);
17             cur = cur.next;
18             carry /= 10;
19         }
20         if (carry == 1) {
21             cur.next = new ListNode(1);
22         }
23         return newHead.next;
24     }

 

Add two numbers

原文:http://www.cnblogs.com/gonuts/p/4406564.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!