码迷,mamicode.com
首页 > 其他好文 > 详细

Add two numbers

时间:2015-04-09 06:20:09      阅读:147      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!